对于允许您按窗口标题的一部分进行搜索的方法,不区分大小写(将搜索所有窗口,而不仅仅是每个进程的第一个窗口)
using System.Runtime.InteropServices;
using System.Text;
var hwnd = GetHandleByTitle("Chrome");
Console.WriteLine(hwnd);
[DllImport("USER32.DLL")]
static extern IntPtr GetShellWindow();
[DllImport("USER32.DLL")]
static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
static IntPtr GetHandleByTitle(string windowTitle)
{
const int nChars = 256;
IntPtr shellWindow = GetShellWindow();
IntPtr found = IntPtr.Zero;
EnumWindows(
delegate (IntPtr hWnd, int lParam)
{
//ignore shell window
if (hWnd == shellWindow) return true;
//get Window Title
StringBuilder Buff = new StringBuilder(nChars);
if (GetWindowText(hWnd, Buff, nChars) > 0)
{
//Case insensitive match
if (Buff.ToString().Contains(windowTitle, StringComparison.InvariantCultureIgnoreCase))
{
found = hWnd;
return true;
}
}
return true;
}, 0
);
return found;
}
delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);