开发者

GetMessage not receiving WM_DEVICECHANGE in my MessageWindow

I am trying to Get WM_DEVICECHANGE in background using Message windows. All the Windows API methods I got from pinvoke.com and tested they work. I am using xbox 360 controller for windows and Logitech G35 headset to test the code but I never get the WM_DEVICECHANGE.

Here is the code:

//Creats Message windwos Win32Core.HWND_MESSAGE=-3
IntPtr hMessageWindow = Win32Core.CreateWindowEx(0, "static", "", 0, 0, 0, 0, 0, Win32Core.HWND_MESSAGE, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

//creat and populate the DEV_BROADCAST_DEVICEINTERFACE struct
DEV_BROADCAST_DEVICEINTERFACE sDeviceFilter = new DEV_BROADCAST_DEVICEINTERFACE();
sDeviceFilter.dbcc_devicetype = (int)DBT_DEVTYP_DEVICEINTERFACE; //DBT_DEVTYP_DEVICEINTERFACE = 0x00000005
sDeviceFilter.dbcc_reserved = 0;
//sDeviceFilter.dbcc_classguid = ; irelevant becouse 开发者_JS百科i am using DEVICE_NOTIFY_ALL_INTERFACE_CLASSES
sDeviceFilter.dbcc_name = "EpicName\0";
sDeviceFilter.dbcc_size = Marshal.SizeOf(sDeviceFilter);

//Marshel sDeviceFilter to hDeviceFilter pointer
IntPtr hDeviceFilter = Marshal.AllocHGlobal(sDeviceFilter.dbcc_size);
Marshal.StructureToPtr(sDeviceFilter, hDeviceFilter, false);

//Register for WM_DEVICECHANGE   DEVICE_NOTIFY_WINDOW_HANDLE =0x00000000 , DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x00000004
//The RegisterDeviceNotification Returns some non 0 value 
IntPtr hDeviceNotification = Win32Core.RegisterDeviceNotification(hMessageWindow, hDeviceFilter, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);

//Message pump
MSG sMsg = new MSG();
while (true)
{
    if (Win32Core.GetMessage(out sMsg, hMessageWindow, 0, 0))
    {
        if (sMsg.message == (int)WM.WM_DEVICECHANGE)
        {
            //Never gets here
        }
    }
    Win32Core.DispatchMessage(ref sMsg);
    sMsg = new MSG();
}

//structs
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DEV_BROADCAST_DEVICEINTERFACE
{
    public int dbcc_size;
    public int dbcc_devicetype;
    public int dbcc_reserved;
    public Guid dbcc_classguid;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]
    public string dbcc_name;
} 


That is a non-queued message and so it does not arrive via the message queue. You don't get it by calling GetMessage(). Rather it is delivered directly to a window. I recommend that you read the MSDN overview topic for Windows messages: About Messages and Message Queues.

The documentation for WM_DEVICECHANGE states how the message is delivered as follows:

A window receives this message through its WindowProc function.

You need to override a WndProc() method to receive this message.

I think you should be able to derive from System.Windows.Forms.Control and override WndProc() to get this notification. What's more you don't need to do this in a background thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜