Why QueryFullProcessImageNameW throws System.AccessViolationException

Pawel Krzyzak 1 Reputation point
2021-02-24T11:48:03.133+00:00

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:

[DllImport("kernel32.dll")]
private static extern bool QueryFullProcessImageNameW(IntPtr hProcess, int flags, StringBuilder text, int count);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("kernel32.dll")]
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?

C#
C#
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,309 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 48,826 Reputation points
    2021-02-24T15:08:19.697+00:00

    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 81,831 Reputation points
    2021-02-24T16:46:42.647+00:00

    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