C gets the implementation of the process's main window handle

  • 2020-05-10 18:42:25
  • OfStack

This is done by calling Win32 API.


public class User32API
{
    private static Hashtable processWnd = null;
    public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);
    static User32API()
    {
        if (processWnd == null)
        {
            processWnd = new Hashtable();
        }
    }
    [DllImport("user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
    public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
    [DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]
    public static extern IntPtr GetParent(IntPtr hWnd);
    [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);
    [DllImport("user32.dll", EntryPoint = "IsWindow")]
    public static extern bool IsWindow(IntPtr hWnd);
    [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
    public static extern void SetLastError(uint dwErrCode);
    public static IntPtr GetCurrentWindowHandle()
    {
        IntPtr ptrWnd = IntPtr.Zero;
        uint uiPid = (uint)Process.GetCurrentProcess().Id;  //  The current process  ID
        object objWnd = processWnd[uiPid];
        if (objWnd != null)
        {
            ptrWnd = (IntPtr)objWnd;
            if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd))  //  Get the handle from the cache 
            {
                return ptrWnd;
            }
            else
            {
                ptrWnd = IntPtr.Zero;
            }
        }
        bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
        //  Enumeration window return  false  And no error number indicates success 
        if (!bResult && Marshal.GetLastWin32Error() == 0)
        {
            objWnd = processWnd[uiPid];
            if (objWnd != null)
            {
                ptrWnd = (IntPtr)objWnd;
            }
        }
        return ptrWnd;
    }
    private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)
    {
        uint uiPid = 0;
        if (GetParent(hwnd) == IntPtr.Zero)
        {
            GetWindowThreadProcessId(hwnd, ref uiPid);
            if (uiPid == lParam)    //  Find the main window handle for the process 
            {
                processWnd[uiPid] = hwnd;   //  Cache the handle 
                SetLastError(0);    //  Setup error free 
                return false;   //  return  false  To terminate the enumeration window 
            }
        }
        return true;
    }
} 

Call User32API.GetCurrentWindowHandle () to return the main window handle of the current process, or IntPtr.Zero if the fetch fails.

--EOF--


Related articles: