3

我有一个 UI 线程的活动窗口GetActiveWindow。如果它是 WPF 弹出窗口,我需要关闭窗口。

如何确定窗口是否是 wpf 窗口?

4

1 回答 1

5

使用HwndSource.

http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndsource.fromhwnd.aspx

如下:

IntPtr hwnd = GetActivewWindow();

HwndSource hwndsrc = HwndSource.FromHwnd(hwnd);

// Use any variation on this code

if (hwndsrc != null && hwndsrc.RootVisual != null)
{
    Window window = hwndsrc.RootVisual as Window;

    if (window != null)
    {
        window.Close();
    }

    // UPDATE: I've added looking for a "Popup" window as well
    // because your question mentions "pop up window"...but
    // not sure if you meant a top-level Window, or a Popup...
    // ....Popup windows have HWND too!

    Popup popupwindow = hwndsrc.RootVisual as Popup;

    if (popupwindow != null)
    {
        popupwindow.IsOpen = false;
    }
}
于 2012-08-24T09:35:55.113 回答