下面的代码执行以下操作
PushWindowToFront():
- 获取当前进程 id 供以后参考
- 使用回调EnumWindowsCallback方法调用 user32.dll 函数EnumWindows
- EnumWindows 然后遍历每个窗口并为每个窗口调用回调
打回来:
- 检查窗口线程进程id是否与当前进程id相同
- 如果是,请检查窗口文本是否开始“选择”
- 如果是这样,在窗口句柄上调用 user32.dll 函数 SetFocus
- 检查并打印最后一个 win32 错误
但是,它总是返回 win32 错误 5 - “访问被拒绝”。为什么应用程序无权针对属于同一进程的窗口调用此函数?
.
public void PushWindowToFront()
{
currentProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
Win32Methods.EnumWindowsCallbackDelegate callback = new Win32Methods.EnumWindowsCallbackDelegate(this.EnumWindowsCallback);
Win32Methods.EnumWindows(callback, (IntPtr) 0);
}
public bool EnumWindowsCallback(IntPtr hWnd, IntPtr lParam)
{
uint i = 0;
Win32Methods.GetWindowThreadProcessId(hWnd, out i);
if (currentProcessId == i)
{
StringBuilder sb = new StringBuilder(512);
Win32Methods.GetWindowText(hWnd, sb, sb.Capacity);
if (sb.ToString().Split(' ')[0].ToLower().Equals("select"))
{
IntPtr result = Win32Methods.SetFocus(hWnd);
Console.WriteLine("Window found: {0}\r\nSetting focus...\r\nResult: {1}\r\nLastError: {2}",
sb.ToString(), result, Marshal.GetLastWin32Error().ToString());
}
}
return true;
}