WinForm Panel: Using Mouse Wheel Scroll Action
So you want to capture mouse wheel event and use the wheel scroll on the panel on your Windows Form application? But there is no explicit action to achieve this goal, right?
The only actions for the mouse events in the action bar for Panel are MouseDown, MouseEnter, MouseHover, MouseLeave, MouseMove, MouseUp (Figure 1). Where's MouseWheel?
Just follow the following steps and you would have this functionality in your windows application in no time.
Figure 1: Panel Actions for MouseEvents
Setting Up MouseWheel Action
Lets assume the name of our panel on the WinForm is MapPanel such as:
private System.Windows.Forms.Panel MapPanel;
Inside the InitializeComponent() function add the following along with your other actions on the MapPanel:
this.MapPanel.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.MapPanel_MouseWheel);
This would allow you to create the MouseWheel action on your Panel.
Creating MouseWheel Action and Other Steps
Step 1
In the MouseEnter and MouseLeave Actions of your Panel write the following code:
01. private void MapPanel_MouseEnter(object sender, EventArgs e)
02. {
03. MapPanel.Focus();
04. }
05.
06. private void MapPanel_MouseLeave(object sender, EventArgs e)
07. {
08. this.ActiveControl = null;
09. }
In the above code, you are actually putting the focus on your Panel so that when MouseWheel action occurs on the Panel, it can capture that properly. If you do not provide your Panel the focus for the current event then MouseWheel action won't work properly. In general the focus of a control is not provided to a Panel because panels are meant to be containers. For this reason you need to set the focus explicitly.
Step 2 (Final Step)
Now use the following code for your MouseWheel action:
01.private void MapPanel_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
02.{
03. if (e.Delta > 0)//Scrolling Up
04. {
05. //Write your code for mouse wheel scroll up/forward here
06. }
07. else //Scrolling Down
08. {
09. //Write your code for mouse wheel scroll down/backward here
10. }
11.}
Here, the Delta property determines whether the mouse wheel has scrolled forward or backward because the value is signed. Additionally, you can use SystemInformation.MouseWheelScrollLines property to see how many lines it can move, etc.
More details
MouseEventArgs.Delta:
https://msdn.microsoft.com/en-us/library/aa299629(v=vs.60).aspx
SystemInformation.MouseWheelScrollLines: