Reputation: 21
I have a winforms application whose UI is designed as multi layer of user controls. I am adding code changes to monitor if my application is idle for a certain amount of time. For that I am monitoring keyboard and mouse events in my base form. Keyboard events are received even when child control is in focus where as mouse events are not received in the base form. Note - child controls covers almost entire main form's area.
approaches which did not work:
I have tried to capture WM_MOUSEMOVE, WM_LBUTTONDOWN in WndProc() of main form. these messages are not captured when mouse is moved on child control
Hooked to MouseMove, MouseClick, KeyDown events in mainform, set KeyPreview and Captrure to true by this, only key events are received, mouse events are not received when child control is in focus
Do not want to use system hooks as it comes with serious security issues
Can somebody tell me what is the easy way to get mouse move events in the main form when child control has the focus? I do not want to make changes in each of the child control as many of them do not inherit from a single base user control class
Upvotes: 0
Views: 118
Reputation: 21
Capture the event on the parent form using a normal event handler then in the form constructor add the following code
foreach (Control control in this.Controls)
{
control.MouseMove += Form1_MouseMove; //where Form1_MouseMove is the name of the event handler
}
if you want to make sure you also capture events in controls that will be added later add the following code
private void Form1_ControlAdded(object sender, ControlEventArgs e)
{
e.Control.MouseMove += Form1_MouseMove;
}
and attach it to the Form.ControlAdded event
See the full example below
namespace mouse_capture_example
{
public partial class Form1 : Form
{
int moveCount = 0;
public Form1()
{
InitializeComponent();
//capture MouseMove event for all controls
foreach (Control control in this.Controls)
{
control.MouseMove += Form1_MouseMove;
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
moveCount++;
Console.WriteLine($"The mouse has been moved {moveCount} times");
}
//capture mouse events for controls being added later
private void Form1_ControlAdded(object sender, ControlEventArgs e)
{
e.Control.MouseMove += Form1_MouseMove;
}
}
}
Upvotes: 1