简体   繁体   English

在WPF中按下按钮后检测鼠标单击的最佳方法

[英]Best way to detect mouse click after pressing a button in WPF

My aim is to create a line tool on a program so that when a button is pressed, the user is able to select two points using the left mouse button and after the second click, a straight line should be drawn between the selected points. 我的目的是在程序上创建一条线工具,以便在按下按钮时,用户能够使用鼠标左键选择两个点,并且在第二次单击后,应该在所选点之间绘制一条直线。

Or something similar to the line tool on Microsoft paint if that's easier. 或与Microsoft Paint上的线条工具类似的工具更简单。 So long as the user can draw a line. 只要用户可以画一条线。

The code I have so far is minimal. 到目前为止,我的代码很少。 The problem I have is detecting a mouse click while inside the function below. 我的问题是在下面的函数内部检测到鼠标单击。 I originally used a while loop with 我最初使用while循环

if (MouseButton.Left == MouseButtonState.Pressed) 

to check for the clicks however I just created an endless loop as the condition was never satisfied. 检查点击,但是由于条件从未满足,所以我创建了一个无限循环。

My only other idea is to use an event within the LineTool_Click function such as drawingCanvas.MouseDown but I have no idea how that would work either :/ I'm new to c# /wpf. 我唯一的其他的想法是使用LineTool_Click等功能中的事件drawingCanvas.MouseDown ,但我不知道如何将工作之一:/我是新来的C#/ WPF。

// When the LineTool button is clicked.....
private void LineTool_Click(object sender, RoutedEventArgs e)
{
   Point startPoint = new Point(0,0);
   Point endPoint = new Point(0, 0);
}

The simplest option is probably to store the start/end points outside of the method, and then check within the method if they've been captured or not: 最简单的选择可能是将起点/终点存储在方法之外 ,然后在方法内检查是否已捕获它们:

// Store these outside of the method
Point lastPoint = new Point(0,0);
bool captured = false;

// When the LineTool button is clicked.....
private void LineTool_Click(object sender, MouseButtonEventArgs e)
{
   if (!this.captured)
   {
       this.captured = true;
       this.lastPoint = e.GetPosition(this.LineTool);
       return;
   }

   // Okay - this is the second click - draw our line:
   this.captured = false; // Make next click "start" again
   Point endPoint = e.GetPosition(this.LineTool);

   // draw from this.lastPoint to endPoint
}

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

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