2010-09-23 149 views
6

我有一个winform,我希望允许用户移动控件。如何允许用户移动窗体上的控件

的控制是(现在)的垂直线:标签与边框和1

宽度的背景是不是很重要,但我会反正给你。我有一些图形背景,我希望用户能够在图形上方滑动指南。图形是用NPlots库制作的。它看起来是这样的: http://www.ibme.de/pictures/xtm-window-graphic-ramp-signals.png

如果我能找出用户如何单击并拖动屏幕周围的标签/线控制,我可以解决我的指导问题。请帮忙。

回答

8

此代码可能会有点复杂,但基本上您需要捕获窗体上的MouseDown,MouseMove和MouseUp事件。类似这样的:

public void Form1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if(e.Button != MouseButton.Left) 
     return; 

    // Might want to pad these values a bit if the line is only 1px, 
    // might be hard for the user to hit directly 
    if(e.Y == myControl.Top) 
    { 
     if(e.X >= myControl.Left && e.X <= myControl.Left + myControl.Width) 
     { 
      _capturingMoves = true; 
      return; 
     } 
    } 

    _capturingMoves = false; 
} 

public void Form1_MouseMove(object sender, MouseEventArgs e) 
{ 
    if(!_capturingMoves) 
     return; 

    // Calculate the delta's and move the line here 
} 

public void Form1_MouseUp(object sender, MouseEventArgs e) 
{ 
    if(_capturingMoves) 
    { 
     _capturingMoves = false; 
     // Do any final placement 
    } 
} 
+0

谢谢!完美的作品。 – Roast 2010-09-24 13:17:14

3

在WinForms中,您可以处理控件的MouseDown,MouseMove和MouseUp事件。在MouseDown上,设置一些位或引用来告诉你的窗体鼠标点击的控件,并从MouseEventArgs中捕获鼠标的X和Y.在MouseMove上,如果设置了控件,请通过上次捕获的X和Y与当前坐标之间的差异来调整X和Y.在MouseUp上,释放控件。

我会为此设置一个“编辑模式”当用户进入这个模式时,你的表单控件的当前事件处理程序应该被分离,并且附加移动处理程序。如果您想要保留或恢复这些更改(例如,您正在创建自定义表单设计器,客户可以使用它来自定义窗口布局),那么您还需要能够对前后布局进行某种快照控制。

0

这里,你可以使用任何控制的扩展方法。它使用Rx,并基于A Brief Introduction to the Reactive Extensions for .NET, Rx的帖子和Wes Dyer的样本。

public static class FormExtensions 
{ 
    public static void EnableDragging(this Control c) 
    { 
     // Long way, but strongly typed.   
     var downs = 
      from down in Observable.FromEvent<MouseEventHandler, MouseEventArgs>(
       eh => new MouseEventHandler(eh), 
       eh => c.MouseDown += eh, 
       eh => c.MouseDown -= eh) 
      select new { down.EventArgs.X, down.EventArgs.Y }; 

     // Short way.   
     var moves = from move in Observable.FromEvent<MouseEventArgs>(c, "MouseMove") 
        select new { move.EventArgs.X, move.EventArgs.Y }; 

     var ups = Observable.FromEvent<MouseEventArgs>(c, "MouseUp"); 

     var drags = from down in downs 
        from move in moves.TakeUntil(ups) 
        select new Point { X = move.X - down.X, Y = move.Y - down.Y }; 

     drags.Subscribe(drag => c.SetBounds(c.Location.X + drag.X, c.Location.Y + drag.Y, 0, 0, BoundsSpecified.Location)); 
    } 
} 

用法:

按钮button1的新=按钮();

button1.EnableDragging();

0

那么在所有的诚实中,有一种更简单的方法,通过初始化一个叫做任何你喜欢的全局布尔变量,在这种情况下,isMouseClicked。在您的控制中,您希望允许拖动您的鼠标按下事件,

确保这些事件是您的控制事件而不是您的表单事件。

if (e.button == MouseButtons.left) 
    //this is where you set the boolean to true 

然后去了鼠标移动事件

if (isMouseClicked == true) 
    //You then set your location of your control. See below: 
    Button1.Location = new Point(MousePosition.X, MousePosition.Y); 

在您的鼠标向上务必设置您的isMouseClickedfalse;

相关问题