【问题标题】:How to destroy a Third Party WPF Child Window using c#?如何使用 c# 销毁第三方 WPF 子窗口?
【发布时间】:2014-03-12 14:14:08
【问题描述】:

我正在尝试销毁由第三方应用程序创建的子窗口。我试图使用 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:拒绝访问。关于解决方法的任何想法?

【问题讨论】:

  • 您是否检查过您的DestroyWindow 调用是否返回错误代码?
  • 返回的错误代码 错误代码 5:访问被拒绝,看来我无法为此销毁它,将更新问题。
  • 这可能是(和 IIRC:是),因为您的调用应用程序不是负责创建窗口的应用程序。您可能需要获得某种上下文/权限才能执行此操作。我不确定所需的步骤
  • 实际上,如果您查看 MSDN 文档上 DestroyWindow 的备注部分:“线程不能使用 DestroyWindow 销毁由不同线程创建的窗口。”
  • 关闭它 p/invoke PostMessage + WM_CLOSE(或使用 UI 自动化)

标签: c# wpf winapi


【解决方案1】:

win32 API DestroyWindow 的文档非常清楚:

线程不能使用 DestroyWindow 来销毁由 不同的线程。

您可以在第三方应用程序中注入 DLL,挂钩正确的线程,然后从此处发出 DestroyWindow 调用,但我将建议这样做,因为它可能有奇怪的副作用(阅读:崩溃)。某些应用程序在其窗口被其脚下破坏时反应不佳。

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

如果用户无法关闭那个窗口,那你就倒霉了。

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多