C#在Win10與非Win10 Windows系統鼠標滾動編程的一點區別。
阿新 • • 發佈:2018-03-07
exc class 按鈕 static -- nta button ren tro
C#在win10和非Win10上處理鼠標滾動有一些區別,建一個Form1,放置一個FlowLayoutPanel ,類型的Panel1
Panel.MouseWheel += PanelOnMouseWheel; private void PanelOnMouseWheel(object sender, MouseEventArgs mouseEventArgs) { if (mouseEventArgs.Delta < 0) ScrollBar.Value = ScrollBar.Value == ScrollBar.Maximum ? ScrollBar.Maximum : ++ScrollBar.Value;else ScrollBar.Value = ScrollBar.Value == ScrollBar.Minimum ? ScrollBar.Minimum : --ScrollBar.Value; }
以上代碼在win10上,只要鼠標在Panel1客戶區範圍內,那麽滾動鼠標滾輪時,就能觸發滾動事件,但是在非win10上,如果焦點不在Panel上,比如在Form1窗體一個Button上,那麽就不能觸發滾動事件。
解決辦法
[DllImport("user32.dll")] public static externIntPtr GetFocus();
需要判斷焦點按鈕是否是本窗口子控件,使用IMessageFilter。
const int WM_MOUSEWHEEL = 0x020A; public bool PreFilterMessage(ref Message msg) { if (msg.Msg == WM_MOUSEWHEEL) { if ((CheckControl(this.Parent, GetFocus()))) {int wpara = (int)msg.WParam; if ((wpara & 0x80000000) == 0x80000000)//向下 ScrollBar.Value = ScrollBar.Value == ScrollBar.Maximum ? ScrollBar.Maximum : ++ScrollBar.Value; else ScrollBar.Value = ScrollBar.Value == ScrollBar.Minimum ? ScrollBar.Minimum : --ScrollBar.Value; } return false; } return false; }
public bool CheckControl(Control control, IntPtr handle) { if (control == null) return false; try { for (int i = 0; i < control.Controls.Count; i++) { var v = control.Controls[i]; if (handle == v.Handle) { return true; } else { if (v.Controls.Count > 0) { if (CheckControl(v, handle)) { return true; } } } } } catch (Exception e) { Console.WriteLine(e); return false; } return false; }
如果有更好的解決辦法請指點。
C#在Win10與非Win10 Windows系統鼠標滾動編程的一點區別。