Menu

#48 WindowsDeviceNotifier won't work when called from MTAThread

v2.2.8
open
nobody
None
5
2014-12-14
2014-12-14
Jay
No

WindowsDeviceNotifier creates a NativeWindow to listen for WM_DEVICECHANGE events, but this only works when messages are getting pumped, which requires an STAThread and Application.Run() to be called. This works fine in WinForms and WPF applications, but in console apps, this is not the case. WindowsDeviceNotifier.cs should be patched to spin up an STAThread and run Application.Run() to work properly:

public void StaThread()
{
mNotifyWindow = new DevNotifyNativeWindow(OnHandleChange, OnDeviceChange);
Application.Run();
}

public WindowsDeviceNotifier()
{
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
mNotifyWindow = new DevNotifyNativeWindow(OnHandleChange, OnDeviceChange);
}
else
{
Thread staThread = new Thread(new ThreadStart(StaThread));
staThread.SetApartmentState(ApartmentState.STA);
staThread.Name = "DevNotifyNativeWindow STA Thread";
staThread.Start();
}
}

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.