繁体   English   中英

C#如何在按下INSERT键后获取鼠标位置,按下按钮后?

[英]C# how to get mouse position after INSERT key if pressed, after button click?

当我按下一个键(插入)时,我需要知道如何获得鼠标位置。

这就是我想要做的:

我有一个带有一个buuton的form1,当你按下那个按钮时它会调用另一个表格。 但在调用form2之前,我需要从外部应用程序获取鼠标位置。 为此,用户必须将光标悬停在请求的位置上并按“插入”。

public partial class _CalibrateGeneralStep2 : Form
{
    public _CalibrateGeneralStep2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Hide();      

        ///// HERE I NEED TO WAIT UNTIL USER PRESS 'INSERT' KEY BEFORE CALL  _CalibrateGeneralStep3 /////   

        _CalibrateGeneralStep3 frm = new _CalibrateGeneralStep3();
        frm.Show();
    }
}

我尝试使用按键和键盘,但我不知道使用它。

谢谢......抱歉,如果我的英语不好......

您可以使用

System.Windows.Forms.Cursor.Position :“它表示屏幕坐标中的当前光标位置”

注意:请参阅示例以了解其工作原理

您可以使用表单的KeyDown事件(您可以从Designer添加它以确保它正确连接)

由于你不能只等待button2_Click中的按键事件,我已经使用私有字段来存储按钮被按下的事实。 现在,每次用户按Insert时,都会检查按钮是否被按下以及光标位置。 如果两者都正确,则生成新表单。

我已经在类的顶部用2个常量定义了所需的光标位置,你还应该为“hasButton2BeenClicked”选择一个更好的名称,具体取决于你的业务环境哈哈。

public partial class _CalibrateGeneralStep2 : Form
{
    private const int NEEDED_X_POSITION = 0;
    private const int NEEDED_Y_POSITION = 0;

    private bool hasButton2BeenClicked = false;

    public _CalibrateGeneralStep2()
    {
        InitializeComponent();
        KeyPreview = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

    private void button2_Click(object sender, EventArgs e)
    {      
        hasButton2BeenClicked = true;  
    }

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Insert && IsCursorAtTheCorrectPosition() && hasButton2BeenClicked)
        {
            GoToNextStep();
        }
    }

    private bool IsCursorAtTheCorrectPosition()
    {
        return Cursor.Position.X == NEEDED_X_POSITION && Cursor.Position.Y == NEEDED_Y_POSITION;
    }

    private void GoToNextStep()
    {
        this.Hide();
        new _CalibrateGeneralStep3().Show();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM