之前有寫了一篇「讓Panel對Mouse滾輪事件(Wheel)有感覺」,是透過 SendMessage 的方式去叫 Panel Scroll。
但是卻不會觸發Panel的Scroll事件。那怎麼辦呢?
在之前有寫了一篇「讓Panel對Mouse滾輪事件(Wheel)有感覺」,是透過 SendMessage 的方式去叫 Panel Scroll。
但是卻不會觸發Panel的Scroll事件。那怎麼辦呢?
所以我們可以透過Control.FromHandle來取到那個控制項,然後再觸發該控制項的Scroll事件,如下,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
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)
{
//取得控制項
ScrollableControl ctrl = Control.FromHandle(hWnd) as ScrollableControl;
int orgValue = 0;
if (ctrl != null)
{
//取得控制項垂直ScrollBar的值
orgValue = ctrl.VerticalScroll.Value;
}
SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
if (ctrl != null)
{
//取得控制項垂直ScrollBar的值
int newValue = ctrl.VerticalScroll.Value;
var se = new ScrollEventArgs(ScrollEventType.ThumbTrack, orgValue, newValue
, ScrollOrientation.VerticalScroll);
FireScrollEvent(ctrl, se);
}
return true;
}
}
return false;
}
/// <summary>
/// 觸發控制項的Scroll事件
/// </summary>
/// <param name="sc"></param>
/// <param name="e"></param>
private void FireScrollEvent(ScrollableControl sc, ScrollEventArgs e)
{
MethodInfo onScroll = sc.GetType().GetMethod("OnScroll",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
onScroll.Invoke(sc, new object[] { e });
}
}
}
參考資料
WinForms: How to programatically fire an event handler?
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^