我最近尝试用C#开发一个简单的WPF应用程序,并且需要获取窗口的HwndSource以便添加事件处理程序。每次运行代码时,我都会在handleSource = HwndSource.FromHwnd(handle);
这一行停止,并出现错误信息System.ArgumentException: 'Hwnd of zero is not valid.'
。据我了解,当窗口没有完全初始化或者没有窗口,或者正在被销毁时,就会发生这种情况。如果我的理解是正确的,那么我不知道为什么会发生这种情况。
我在谷歌上没有找到其他人有相同的问题,下面是我的代码。
public partial class MainWindow:Window {
SimConnect simConnect;
bool connectedToSim = false;
/// Window handle
IntPtr handle;
HwndSource handleSource;
const int WM_USER_SIMCONNECT = 0x0402;
/// <summary>
/// Constructor and starting for the window
/// </summary>
public MainWindow() {
InitializeComponent();
handle = new WindowInteropHelper(this).Handle; // Get handle of main WPF Window
handleSource = HwndSource.FromHwnd(handle); // Get source of handle in order to add event handlers to it
handleSource.AddHook(HandleSimConnectEvents);
Thread pollThread = new Thread(PollThread);
}
~MainWindow() {
if (handleSource != null) {
handleSource.RemoveHook(HandleSimConnectEvents);
}
}
private IntPtr HandleSimConnectEvents(IntPtr hWnd, int message, IntPtr wParam, IntPtr lParam, ref bool isHandled) {
isHandled = false;
switch (message) {
case WM_USER_SIMCONNECT: {
if (simConnect != null) {
simConnect.ReceiveMessage();
isHandled = true;
}
}
break;
default:
break;
}
return IntPtr.Zero;
}
}
非常感谢您的帮助!
EnsureHandle
,即构造函数。如果原生窗口尚未创建,则此方法将创建原生窗口,设置 Handle 属性并返回 HWND。如果原生窗口已经被创建,则返回现有原生窗口的句柄。 - TheGeneral