1 // OpenTween - Client of Twitter
2 // Copyright (c) 2015 kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
3 // All rights reserved.
5 // This file is part of OpenTween.
7 // This program is free software; you can redistribute it and/or modify it
8 // under the terms of the GNU General Public License as published by the Free
9 // Software Foundation; either version 3 of the License, or (at your option)
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 // You should have received a copy of the GNU General Public License along
18 // with this program. If not, see <http://www.gnu.org/licenses/>, or write to
19 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 // Boston, MA 02110-1301, USA.
23 using System.Collections.Generic;
26 using System.Reflection;
28 using System.Threading.Tasks;
29 using System.Windows.Forms;
34 /// コントロールにフォーカスが当たってなくても無理矢理 MouseWheel イベントを発生させるクラス
36 public class MouseWheelMessageFilter : IMessageFilter
38 private readonly List<Control> controls = new List<Control>();
40 public MouseWheelMessageFilter()
41 => Application.AddMessageFilter(this);
43 public void Register(Control target)
44 => this.controls.Add(target);
46 public void Unregister(Control target)
47 => this.controls.Remove(target);
49 public bool PreFilterMessage(ref Message m)
51 const int WM_MOUSEWHEEL = 0x020A;
53 if (m.Msg == WM_MOUSEWHEEL)
55 foreach (var control in this.controls)
57 var details = ParseMessage(m);
58 var controlRectangle = control.Parent.RectangleToScreen(control.DisplayRectangle);
59 if (controlRectangle.Contains(details.ScreenLocation))
61 var clientLocation = control.PointToClient(details.ScreenLocation);
63 var ev = new HandledMouseEventArgs(MouseButtons.None, 0, clientLocation.X, clientLocation.Y, details.WheelDelta);
64 this.RaiseMouseWheelEvent(control, ev);
66 // フォーカスが当たっているか否かに関わらず OnMouseWheel イベントを発生させているため、
67 // 二重にイベントが発生することを防ぐために標準のメッセージ処理は抑制する
76 internal class MouseEvent
78 public Point ScreenLocation { get; }
79 public int WheelDelta { get; }
81 public MouseEvent(Point location, int delta)
83 this.ScreenLocation = location;
84 this.WheelDelta = delta;
88 internal static MouseEvent ParseMessage(Message m)
90 var screenLocation = new Point((int)(m.LParam.ToInt64() & 0xffffffff));
91 var wheelDelta = (int)(m.WParam.ToInt64() & 0xffff0000) >> 16;
93 return new MouseEvent(screenLocation, wheelDelta);
96 public void RaiseMouseWheelEvent(Control control, MouseEventArgs e)
98 var method = typeof(Control).GetMethod("OnMouseWheel", BindingFlags.Instance | BindingFlags.NonPublic);
99 method.Invoke(control, new[] { e });