SoFunction
Updated on 2025-03-07

Implementation method of obtaining the main window handle of a C# process


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("", EntryPoint = "EnumWindows", SetLastError = true)]
    public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);

    [DllImport("", EntryPoint = "GetParent", SetLastError = true)]
    public static extern IntPtr GetParent(IntPtr hWnd);

    [DllImport("", EntryPoint = "GetWindowThreadProcessId")]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);

    [DllImport("", EntryPoint = "IsWindow")]
    public static extern bool IsWindow(IntPtr hWnd);

    [DllImport("", EntryPoint = "SetLastError")]
    public static extern void SetLastError(uint dwErrCode);

    public static IntPtr GetCurrentWindowHandle()
    {
        IntPtr ptrWnd = ;
uint uitPid = (uint)().Id;  // Current process ID
        object objWnd = processWnd[uiPid];

        if (objWnd != null)
        {
            ptrWnd = (IntPtr)objWnd;
if (ptrWnd != && IsWindow(ptrWnd)) // Get the handle from the cache
            {
                return ptrWnd;
            }
            else
            {
                ptrWnd = ;
            }
        }

        bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
// When the enumeration window returns false and there is no error number, it indicates that the acquisition is successful
        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) == )
        {
            GetWindowThreadProcessId(hwnd, ref uiPid);
if (uiPid == lParam)    // Find the main window handle corresponding to the process
            {
processWnd[uiPid] = hwnd;   // Cache the handle
SetLastError(0);     // No errors in setting
return false;   // Return false to terminate the enumeration window
            }
        }

        return true;
    }
}