【问题标题】:Getting mouse click position in pictureBox C#在pictureBox C#中获取鼠标点击位置
【发布时间】:2022-01-15 19:22:55
【问题描述】:

我正在尝试获取图片框上的鼠标点击坐标并将信息放入文本框中。

我能够在表单中获取鼠标单击坐标,但无法在图片框中获取鼠标坐标(当我在图片框中单击时没有任何反应)。我已经查看了 stackoverflow 上类似问题的答案,但似乎没有什么对我有用。

这是我的完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace testGraphiqueCSharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);
            textBox1.Text = e.X.ToString();
            textBox2.Text = e.Y.ToString();
        }

       private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            textBox1.Text = e.X.ToString();
            textBox2.Text = e.Y.ToString();
            Console.WriteLine("mouse up");
        }
    }
}

【问题讨论】:

  • 你的代码在我的电脑上运行。

标签: c# picturebox


【解决方案1】:
private void pictureBox1_Click(object sender, EventArgs e)
{
    var mouseEventArgs = e as MouseEventArgs;
    if (mouseEventArgs != null) textBox1.Text = "X= " + mouseEventArgs.X + " Y= " + mouseEventArgs.Y;
}

【讨论】:

  • 谢谢!最初我无法投射鼠标事件...以上解决了问题!
【解决方案2】:

你的代码很完美,可以在我的电脑上运行
Please make sure that that event is actually called by putting debug point.
这是相同的图像
UI 部分


代码部分

输出(当我点击图片时)

【讨论】:

  • 我放了一个 Console.WriteLine("mouse up"); pictureBox1_MouseUp 中的消息,这永远不会显示在输出窗口中!似乎这个事件永远不会被调用!为什么会这样?!?
【解决方案3】:

当 mouseup 事件发生时,您已经调用了该函数。您应该在点击图片框时调用该函数。尝试点击事件等事件来完成您的任务。

【讨论】:

    【解决方案4】:

    用这个替换pictureBox1_MouseUp

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        MouseEventArgs eM = (MouseEventArgs)e;
        textBox1.Text = eM.X.ToString();
        textBox2.Text = eM.Y.ToString();
        Console.WriteLine("mouse up");
    }
    

    【讨论】:

      【解决方案5】:

      这对我有用。我把这段代码放在了表单的构造函数中。

      pictureBox1.MouseClick += (s, e) => MessageBox.Show(String.Format("Mouse Clicked at X: {0} Y: {1}", e.X, e.Y));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 1970-01-01
        • 2015-02-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多