【发布时间】:2011-03-14 07:49:03
【问题描述】:
我需要访问一些 WPF 窗口的 Win32 窗口句柄,以便处理 Win32 激活消息。我知道我可以使用 PresentationSource.FromVisual 或 WindowInteropHelper 来获取 Win32 窗口句柄,但是如果尚未创建 WPF 窗口,我就会遇到问题。
如果我使用PresentationSource.FromVisual,并且没有创建窗口,则返回的PresentationSource 为空。如果我使用WindowInteropHelper 并且没有创建窗口,则Handle 属性为IntPtr.Zero (null)。
在尝试访问句柄之前,我尝试在窗口上调用this.Show() 和this.Hide()。然后我可以得到句柄,但窗口在屏幕上瞬间闪烁(丑陋!)。
有人知道强制创建 WPF 窗口的方法吗?在 Windows 窗体中,这就像访问 Form.Handle 属性一样简单。
编辑:我最终选择了 Chris Taylor 答案的变体。在这里,以防它帮助别人:
static void InitializeWindow(Window window)
{
// Get the current values of the properties we are going to change
double oldWidth = window.Width;
double oldHeight = window.Height;
WindowStyle oldWindowStyle = window.WindowStyle;
bool oldShowInTaskbar = window.ShowInTaskbar;
bool oldShowActivated = window.ShowActivated;
// Change the properties to make the window invisible
window.Width = 0;
window.Height = 0;
window.WindowStyle = WindowStyle.None;
window.ShowInTaskbar = false;
window.ShowActivated = false;
// Make WPF create the window's handle
window.Show();
window.Hide();
// Restore the old values
window.Width = oldWidth;
window.Height = oldHeight;
window.WindowStyle = oldWindowStyle;
window.ShowInTaskbar = oldShowInTaskbar;
window.ShowActivated = oldShowActivated;
}
// Use it like this:
InitializeWindow(myWpfWindow);
【问题讨论】:
-
你见过这个问题吗 - stackoverflow.com/questions/1556182/… - 它可能没有帮助,因为它没有提到窗口是否已经存在。
-
@ChrisF:谢谢!是的,我已经看到了。不幸的是,它的问题是尚未创建窗口。
-
我想我会提到它以获得您的回复,这样如果您的情况不同,它就不会被选为重复。
-
你真的需要提前触发句柄创建吗?还是您只需要在显示之前操纵手柄? IIRC,您可以为此使用 SourceInitialized 事件。