Why QueryFullProcessImageNameW throws System.AccessViolationException

Pawel Krzyzak 1 Reputation point

Hello everyone,

What I would like to accomplish is to retrieve the full name of the executable program for the specified process.
It is a reason why I am trying to use the QueryFullProcessImageNameA function from the Kernel32.dll.

It is part of my code:

private static extern bool QueryFullProcessImageNameW(IntPtr hProcess, int flags, StringBuilder text, int count);
private static extern IntPtr GetForegroundWindow();
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
private static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
IntPtr handle = GetForegroundWindow();
const int nChars = 1024;
StringBuilder strBuilder = new StringBuilder(nChars);
GetWindowThreadProcessId(handle, out int processId);
IntPtr hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId);
QueryFullProcessImageNameW(hProc, 0, strBuilder, nChars);

But QueryFullProcessImageNameW function throws the System.AccessViolationException exception. Don't know why and how can I fix it. Do you have any suggestions?

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,619 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 51,016 Reputation points

    Your import statements do not properly handle charset and unmanaged types resulting in memory corruption.

    [DllImport("kernel32.dll", CharSet=CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool QueryFullProcessImageNameW ( IntPtr hProcess, int flags, StringBuilder text, ref int count );
    //To call - make nChars not const
    QueryFullProcessImageNameW(hProc, 0, strBuilder, ref nChars);
    0 comments No comments

  2. Castorix31 83,101 Reputation points

    And you can see old MSDN threads, like Win10 + c# WindowHandle and Process.Id issue with ApplicationFrameHost.exe
    where I had posted a code sample

    0 comments No comments