Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the form name when mouse is position on any SDI form

i was looking for trick to get the form name when mouse is place on it. suppose i have one mdi form and many sdi form like form1,form2,form3 and all sdi form are opened. suppose i have one timer running on form1 and which will run periodically. i want to show the form name on form1's label from the timer tick event when mouse is positioned on any SDI form window.

this way i try to do it. here is the code

private void timer1_Tick(object sender, EventArgs e) {
    var handle = WindowFromPoint(Cursor.Position);
    if (handle != IntPtr.Zero) {
        var ctl = Control.FromHandle(handle);
        if (ctl != null) {
            label1.Text = ctl.Name;
            return;
        }
    }
    label1.Text = "None";
}

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(Point pos);

the above code run perfectly but there is some glitch. when i place my mouse on MDI form or on Form1 then form name is showing on form1 but when i place the mouse on Form2 or Form2 then their name is not showing. i am not being able to understand what is the problem in this code. please guide me to fix it.

like image 274
Thomas Avatar asked Nov 13 '22 09:11

Thomas


1 Answers

Since you have the control, I think you just need to use the FindForm() function:

var ctl = Control.FromHandle(handle);
if (ctl != null) {
  var form = ctrl.FindForm();
  if (form != null) {
    label1.Text = form.Name;
  }
}
like image 134
LarsTech Avatar answered Nov 15 '22 12:11

LarsTech