如何使用c#销毁第三方WPF子窗口?

时间:2014-03-12 14:14:08

标签: c# wpf winapi

我正在尝试销毁由第三方应用程序创建的子窗口。我尝试使用WinApi来实现这一点,但似乎DestroyWindow(hwnd)并没有做到这一点。我确实得到了一个工作的句柄,但没有任何反应,子窗口仍然存在。我试图使用CloseWindow(hwnd)来验证子窗口是否可以修改,是的,CloseWindow(hwnd)最小化子窗口,但我想关闭它。

这是我的代码:

[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DestroyWindow(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseWindow(IntPtr hWnd);

private static void CloseChildWindow();
{
  IntPtr _hwnd = IntPtr.Zero;

  if (WindowController.FindWindow(null, "System Alert") != IntPtr.Zero)
  {
    _hwnd = WindowController.FindWindow(null, "System Alert");
    DestroyWindow(_hwnd); //Returns error code 5: Access Denied
    CloseWindow(_hwnd); //Minimizes the window therefore _hwnd is correct
  }
}

提前感谢任何有关正在发生的事情或解决方法的想法。

EDIT1:Destroywindow返回代码错误5:访问被拒绝。有关解决方法的任何想法吗?

1 个答案:

答案 0 :(得分:0)

win32 API DestroyWindow的文档非常明确:

  

线程无法使用DestroyWindow来销毁由a创建的窗口   不同的主题。

您可以在第三方应用程序中注入DLL,挂钩正确的线程,然后从此处发出DestroyWindow来电,但我会建议,因为它可能有奇怪的副作用(阅读:崩溃)。有些应用程序在窗户被脚下摧毁时反应不佳。

正确的方法可能是伪造用户交互,使用常规Windows消息(WM_CLOSE),SendInput或UI自动化。

如果用户无法关闭该窗口,则表示运气不佳。