让Panel对Mouse滚轮事件(Wheel)有感觉
最近有看到朋友谈到“panel 选轴捆动与 textbox 疑问”。
如果TextBox在Panel中的话,Focus在TextBox上,滑动Mouse滚轮的话,如果Panel有Scroll的话,是会跟着滑动的!
但是如果Focus所在的TextBox不在Panel之中,那Mouse在有Scroll的Panel上滑动Mouse滚轮,panel是不会理你的哦!
因为Panel默认是不会吃Focus的哦! 而且目前Focus是在Panel外面的TextBox上,不可以切换Focus过来!
那要如何做呢?
在网络上有找到解法“Mouse Wheel Event (C#)”,马上记录下来。
在Winform上放了一个Panel里面放了一堆Button,并设定AutoScroll=True,再放一个TextBox在Panel外面,如下的画面,
而程序中作法如下,
1.您的form要实践 IMessageFilter
2.加入PreFilterMessage method
3.在Form的建构函数中加入Application.AddMessageFilter(this);
Code如下,
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form, IMessageFilter
{
// P/Invoke declarations
[DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(Point pt);
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);
}
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == 0x20a)
{
// WM_MOUSEWHEEL, find the control at screen position m.LParam
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
IntPtr hWnd = WindowFromPoint(pos);
if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null)
{
SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
return true;
}
}
return false;
}
}
}
有AutoScroll属性的Container控件,应该都是有效的哦!
原文:大专栏 [WIN]让Panel对Mouse滚轮事件(Wheel)有感觉