How to determine form name when mouse is in any SDI form

I was looking for a trick to get the name of the form when the mouse is on it. Suppose I have one mdi form, and many sdi forms, such as form1, form2, form3 and all sdi forms, are open. Suppose I have one timer running on form1 and that will run periodically. I want to show the form name on the label form1 from the timer event when the mouse is located in any window of the SDI form.

so I'm trying 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);

, . MDI Form1, 1, Form2 Form2, . , . , , .

+5
2

, , FindForm():

var ctl = Control.FromHandle(handle);
if (ctl != null) {
  var form = ctrl.FindForm();
  if (form != null) {
    label1.Text = form.Name;
  }
}
+1

, Form2 , , Form2, , . , , Program.cs:

MDIParent mdi = new MDIParent();
Form1 frm1 = new Form1();
frm1.MdiParent = mdi;
Form2 frm2 = new Form2();
frm2.MdiParent = mdi;
frm1.Show();
frm2.Show();
Application.Run(mdi);

, , Form2 . , !

, , 2, . , , , InitializeComponent. . , "Form3" :

private void InitializeComponent()
{
    this.components = new System.ComponentModel.Container();
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.Text = "Form3";
}

:

private void InitializeComponent()
{
    this.label1 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    // 
    // label1
    // 
    this.label1.AutoSize = true;
    this.label1.Location = new System.Drawing.Point(13, 13);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(35, 13);
    this.label1.TabIndex = 0;
    this.label1.Text = "label1";
    // 
    // Form3
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(284, 262);
    this.Controls.Add(this.label1);
    this.Name = "Form3";
    this.Text = "Form3";
    this.ResumeLayout(false);
    this.PerformLayout();

}

, , . , , , , , .

0

All Articles