2015-01-26 107 views
2

我的目标是在程序上创建一个线条工具,以便当按下按钮时,用户可以使用鼠标左键选择两个点,第二次点击时,应在所选点之间绘制直线。在WPF中按下按钮后检测鼠标点击的最佳方法

或者类似于微软油漆上的线条工具,如果更容易。只要用户可以绘制一条线。

我到目前为止的代码很少。我遇到的问题是在下面的函数中检测到鼠标点击。我最初使用了一个while循环与

if (MouseButton.Left == MouseButtonState.Pressed) 

检查点击,但是我刚刚创建了一个无限循环,因为条件从未满足。

我唯一的想法是在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); 
} 

回答

0

最简单的方法可能是存储开始/结束点以外的方法,然后在方法中检查,如果他们已经被逮捕或不:

// 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 
} 
+0

我可能是在这里真的很愚蠢,但我得到这个错误:'LineTool_Click'没有超载匹配委托'System.Windows.RoutedEventHandler' – user2874417 2015-01-26 19:43:27

+0

@ user2874417你提到你在做一个MouseDown处理程序,而不是一个点击处理程序。你需要适应,如果你想使用点击;) – 2015-01-26 21:41:02

+0

为了澄清,我有一个按钮,在按下时,我想它进入一个'绘图模式',用户只需点击两次,点击。该按钮被命名为LineTool,LineTool_Click被设置为在第一次点击该按钮时运行。 – user2874417 2015-01-26 22:02:09