Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call GetGUIThreadInfo in c#

Tags:

.net

winapi

I have a window handle and am trying to call GetGUIThreadInfo by passing in the window's process id. I am always getting an error "Parameter incorrect" on the call to GetGUIThreadInfo and I can figure out why. Has anyone got this to work?

[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetGUIThreadInfo(unit hTreadID, ref GUITHREADINFO lpgui);

[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(unit hwnd, out uint lpdwProcessId);

[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int iLeft;
    public int iTop;
    public int iRight;
    public int iBottom;
}

[StructLayout(LayoutKind.Sequential)]
public struct GUITHREADINFO
{
    public int cbSize;
    public int flags;
    public IntPtr hwndActive;
    public IntPtr hwndFocus;
    public IntPtr hwndCapture;
    public IntPtr hwndMenuOwner;
    public IntPtr hwndMoveSize;
    public IntPtr hwndCaret;
    public RECT rectCaret;
}

public static bool GetInfo(unit hwnd, out GUITHREADINFO lpgui)
{ 
    uint lpdwProcessId;
    GetWindowThreadProcessId(hwnd, out lpdwProcessId);

    lpgui = new GUITHREADINFO();
    lpgui.cbSize = Marshal.SizeOf(lpgui);

    return GetGUIThreadInfo(lpdwProcessId, ref lpgui); //<!- error here, returns false
}
like image 756
Jeremy Avatar asked Dec 03 '25 01:12

Jeremy


1 Answers

I think you're using the wrong value from the call to GetWindowThreadProcessId, if you look at the documentation here, you'll see that the second parameter is a process ID (as you've named it) but the thread ID is in the return value.

So in other words, I think your code should be like this (untested):

public static bool GetInfo(unit hwnd, out GUITHREADINFO lpgui)
{ 
    uint lpdwProcessId;
    uint threadId = GetWindowThreadProcessId(hwnd, out lpdwProcessId);

    lpgui = new GUITHREADINFO();
    lpgui.cbSize = Marshal.SizeOf(lpgui);

    return GetGUIThreadInfo(threadId, ref lpgui); 
}
like image 86
Hans Olsson Avatar answered Dec 05 '25 13:12

Hans Olsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!