コード例 #1
0
        public static IntPtr FindProcessWindow(string processName)
        {
            var hwndFound = IntPtr.Zero;

            bool enumWindowsProc(IntPtr hwnd, IntPtr lparam)
            {
                if (!WinApi.IsWindowVisible(hwnd))
                {
                    return(true);
                }

                WinApi.GetWindowThreadProcessId(hwnd, out var pid);
                if (pid == 0)
                {
                    return(true);
                }

                var hProcess = WinApi.OpenProcess(WinApi.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);

                if (hProcess == IntPtr.Zero)
                {
                    return(true);
                }
                try
                {
                    var buffer = new StringBuilder(1024);
                    int size   = buffer.Capacity;
                    if (WinApi.QueryFullProcessImageName(hProcess, 0, buffer, out size))
                    {
                        var path     = buffer.ToString();
                        var fileName = System.IO.Path.GetFileNameWithoutExtension(path);
                        if (String.Compare(fileName, processName, ignoreCase: true) == 0)
                        {
                            hwndFound = hwnd;
                            return(false);
                        }
                    }
                }
                finally
                {
                    WinApi.CloseHandle(hProcess);
                }
                return(true);
            }

            WinApi.EnumDesktopWindows(IntPtr.Zero, enumWindowsProc, IntPtr.Zero);
            return(hwndFound);
        }