I am experiencing a problem in my C# code.
A bit of background: I am working on an HMI where I need to detect mouse movement anywhere on the HMI screen. The screen is divided into many different controls, so I use this recursive function in order to be able to detect a mouse movement over any control:
private void SetMouseTriggers(Control c1)
{
// For all of the child controls in this control
for (int i = 0; i < c1.Controls.Count; i++)
{
// Get the individual child control
Control c2 = c1.Controls[i];
// Add a MouseEventHandler to this control's MouseMove event
c2.MouseMove += new MouseEventHandler(OnMouseMove);
// Recursively call this function
SetMouseTriggers(c2);
}
}
// This function is entered whenever the mouse moves anywhere on screen
private void OnMouseMove(object sender, MouseEventArgs e)
{
}
I call this function for the parent control (i.e. SetMouseTriggers(ParentControl)
) to check all child controls. This part works fine.
My issue is that I encounter an error "Cannot access a disposed object" when I attempt to use a specific feature of the HMI, which is to change users.
The strange part is, the error only occurs when the mouse is located over certain controls of the HMI. When the mouse is located over other HMI controls, the program works with no issues.
I tried to debug the program but I don't have access to the source of where the problem is actually occurring.
If it helps, here is the disassembly:
My next thought was to check the isDisposed
property of each control to see if I can at least determine which control is causing the problem. See below the recursive function I created to detect this. I placed the program into debug mode and set a breakpoint if the control was disposed, but I could never hit this breakpoint in various scenarios that I tested.
private void CheckAllControls(System.Windows.Forms.Control c1)
{
// For all of the child controls in this control
for (int i = 0; i < c1.Controls.Count; i++)
{
// Get the individual child control
System.Windows.Forms.Control c2 = c1.Controls[i];
// Check if the control is disposed
if (c2.IsDisposed)
{ // Breakpoint set here
}
// Recursively call this function
CheckAllControls(c2);
}
}
This tells me that the control must be disposed somewhere in the System.Windows.Forms.dll library.
My questions are:
Is there a way around this even though I don't have access to the code where the problem is occurring?
Even if there isn't a way around this, can someone explain what is happening and why? (i.e. Why is this problem only occurring when the mouse is located over certain controls?)