private HwndSource _source; private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { const int WM_LBUTTONDOWN = 0x0201; if (msg == WM_LBUTTONDOWN) { MessageBox.Show("Left Mouse Button clicked"); handled = true; } return IntPtr.Zero; } private void Window_Loaded(object sender, RoutedEventArgs e) { _source = PresentationSource.FromVisual(this) as HwndSource; _source.AddHook(WindowProc); }
private HwndSource _source; private const int WM_DEVICECHANGE = 0x0219; private const int DBT_DEVICEREMOVECOMPLETE = 0x8004; private const int DBT_DEVICEARRIVAL = 0x8000; private const int DBT_DEVTYP_VOLUME = 0x00000002; private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == WM_DEVICECHANGE) { int eventType = wParam.ToInt32(); if (eventType == DBT_DEVICEARRIVAL || eventType == DBT_DEVICEREMOVECOMPLETE) { DEV_BROADCAST_VOLUME volInfo = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(lParam, typeof(DEV_BROADCAST_VOLUME)); if (volInfo.dbcv_devicetype == DBT_DEVTYP_VOLUME) { DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { if ((volInfo.dbcv_unitmask & (1 << (drive.Name.First() - 'A'))) != 0) { if (eventType == DBT_DEVICEARRIVAL) MessageBox.Show("Drive " + drive.Name + " plugged in"); else MessageBox.Show("Drive " + drive.Name + " unplugged"); } } } } } return IntPtr.Zero; } private void Window_Loaded(object sender, RoutedEventArgs e) { _source = PresentationSource.FromVisual(this) as HwndSource; _source.AddHook(WindowProc); } [StructLayout(LayoutKind.Sequential)] public struct DEV_BROADCAST_VOLUME { public int dbcv_size; public int dbcv_devicetype; public int dbcv_reserved; public int dbcv_unitmask; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, int Flags);In this example, we intercept the WM_DEVICECHANGE message to monitor audio device changes. The package library used here is System.Runtime.InteropServices.