WPF處理Windows消息


WPF中處理消息首先要獲取窗口句柄,創建HwndSource對象 通過HwndSource對象添加消息處理回調函數.

HwndSource類: 實現其自己的窗口過程。 創建窗口之后使用 AddHook 和 RemoveHook 來添加和移除掛鈎,接收所有窗口消息。

 private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;//窗口過程
            if (hwndSource != null)
                hwndSource.AddHook(new HwndSourceHook(WndProc));//掛鈎
            
        }

HwndSourceHook 類:委托,處理 Win32 窗口消息的方法。

實例:監測U盤的插入和拔出。

public const int WM_DEVICECHANGE = 0x219;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
           
            if (msg == WM_DEVICECHANGE)
            {
                switch (wParam.ToInt32())
                {
                   
                    case DBT_DEVICEARRIVAL://U盤插入  
                        m_selBox.Items.Clear();
                        InitCombox();                     
                        break;
                                                                                              
                    case DBT_DEVICEREMOVECOMPLETE: //U盤卸載
                        m_selBox.Items.Clear();
                        InitCombox();                        
                        break;
                                                                                             
                    default:
                        break;
                }
            }          
            return IntPtr.Zero;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM