Get cursor position with respect to the control - C#

前端 未结 11 2344
迷失自我
迷失自我 2020-12-05 23:23

I want to get the mouse position with respect to the control in which mouse pointer is present. That means when I place the cursor to the starting point (Top-Left corner) of

11条回答
  •  抹茶落季
    2020-12-05 23:31

    Create af standard Project C# WinForms

    Place 2 Textboxes named X and Y, and a Timer object from the toolbox to the Design page

    Press [F7] and replace all code with below.

    using System;
    using System.Windows.Forms;
    
    namespace MousePos
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                timer1.Start();
            }
    
            private void Form1_MouseCaptureChanged(object sender, EventArgs e)
            {
                X.Text = MousePosition.X.ToString();
                Y.Text = MousePosition.Y.ToString();
            }
        }
    }
    

    Set Timer.Tick action to "Form1_MouseCaptureChanged"

    [F5] Run - and now you have an MosusePos app.

提交回复
热议问题