光标位置 C# 不适用于 pictureBox

Cursor position C# doesn't work over pictureBox

我想获取光标在表单上的位置。

下面的代码有效,但当光标位于某些图片框上时无效。

所以我需要一些帮助。

谢谢!

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    Point p = Cursor.Position;

    label1.Text = "x= " + p.X.ToString();
    label2.Text = "y= " + p.Y.ToString();
}

我想这是因为您仅重写了 OnMouseMove - 表单的方法。要在您的图片框(或任何控件)中捕获鼠标移动事件,请使用控件中的 MouseMove - 事件。

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    Point p = Cursor.Position;

    label1.Text = "x= " + p.X.ToString();
    label2.Text = "y= " + p.Y.ToString();
}

您必须订阅该图片框的 MouseMove 事件并在其中调用您的方法。

// in Form1.cs

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    OnMouseMove(e);
}

或者您可以将表单的 CreateControlsInstance 方法覆盖为 return 自定义控件集合,该集合将订阅每个子控件的 MouseMove 事件

// in Form1.cs

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    Point p = Cursor.Position;

    label1.Text = "x= " + p.X.ToString();
    label2.Text = "y= " + p.Y.ToString();
}

class Form1ControlCollection : ControlCollection
{
    Form1 owner;
    internal Form1ControlCollection(Form1 owner) : base(owner)
    {
        this.owner = owner;
    }

    public override void Add(Control value)
    {
        base.Add(value);
        value.MouseMove += Value_MouseMove;
    }

    private void Value_MouseMove(object sender, MouseEventArgs e)
    {
        owner.OnMouseMove(e);
    }
}

protected override Control.ControlCollection CreateControlsInstance()
{
    return new Form1ControlCollection(this);
}

将此代码段添加到您的表单中

谢谢大家!

这对我有用。

In protected override void OnMouseMove(MouseEventArgs e) 您可以同时使用注释或取消注释代码

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        OnMouseMove(e);
    }

    private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
    {
        OnMouseMove(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        //base.OnMouseMove(e);

        //Point p = Cursor.Position;

        //label1.Text = "x= " + p.X.ToString();
        //label2.Text = "y= " + p.Y.ToString();

        label1.Text = "x= " + e.X.ToString();
        label2.Text = "y= " + e.Y.ToString();        
    }