我需要访问一些我的WPF窗口的Win32窗口句柄,以便处理Win32激活消息。我知道可以使用 PresentationSource.FromVisual
或WindowInteropHelper
来获取Win32窗口句柄,但如果WPF窗口尚未创建,则会遇到问题。
如果使用PresentationSource.FromVisual
并且窗口尚未创建,则返回的PresentationSource
为null。 如果使用WindowInteropHelper
并且窗口尚未创建,则Handle
属性是IntPtr.Zero
(null)。
我尝试在访问句柄之前调用窗口的this.Show()
和this.Hide()
方法。然后我就可以获取句柄,但窗口会瞬间闪烁出现在屏幕上(不美观!)。
有人知道强制创建WPF窗口的方法吗?在Windows Forms中,这就像访问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);