双击标签打开表格C#

时间:2016-02-23 12:40:16

标签: c# winforms

我在labeldouble clicked时尝试打开新表单。我能够拖放标签。我现在试图双击标签打开一个新表格。

  private void control_MouseDown(object sender, MouseEventArgs e)
    {
        var control = sender as Control;
        this.DoDragDrop(control.Name, DragDropEffects.Move);
    }
    private void control_DoubleClick(object sender, EventArgs e)
    {
        frm = new Frm();
        frm.ShowDialog();
        frm.Dispose();
    }

编辑1: 我在下面尝试了两个可能的答案,但他们没有为我工作?

4 个答案:

答案 0 :(得分:3)

更简洁的方法是(注意我将Frm更改为Form1):

private void control_DoubleClick(object sender, EventArgs e)
{

    using (Form1 frm = new Form1())
   {
        frm.ShowDialog();
   }
}

答案 1 :(得分:2)

您无法在DragDrop上添加MouseDown,然后DoubleClick。那不行。

我认为没有一种简单的方法可以解决这个问题,但是一旦拖动控件,它就不会响应双击消息。

我做了一些快速测试,并且有一种“hacky”方式。它会使你的拖动看起来很奇怪(因为它会在一段时间后开始,而不是在你按下鼠标按钮后立即开始),但是它在这里:

private bool _willDrag = false;

private bool control_MouseUp(object sender, MouseEventArgs e)
{
  // disable dragging if we release the mouse button
  _willDrag = false;
}

private bool control_DoubleClick(object sender, EventArgs e)
{
  // disable dragging also if we double-click
  _willDrag = false;

  // .. the rest of your doubleclick event ...
}

private void control_MouseDown(object sender, MouseEventArgs e)
{
  var control = sender as Control;
  if (control == null)
    return;

  _willDrag = true;
  var t = new System.Threading.Timer(s =>
  {
    var callingControl = s as Control;
    if (callingControl == null)
      return;

    // if we released the mouse button or double-clicked, don't drag
    if(!_willDrag)
      return;

    _willDrag = false;
    Action x = () => DoDragDrop(callingControl.Name, DragDropEffects.Move);
    if (control.InvokeRequired)
      control.Invoke(x);
    else
      x();
  }, control, SystemInformation.DoubleClickTime, Timeout.Infinite);
}

答案 2 :(得分:1)

在form.Designer中右键单击你的标签然后属性,在属性窗口中单击事件(迅雷图标),在double_Click事件下拉列表中选择事件处理程序(control_DoubleClick)此方法必须有两个参数objecteventArgs

enter image description here

答案 3 :(得分:1)

这很棘手,因为DoDragDrop吃掉任何进一步的鼠标事件,而MSDN posting a rather stupid example并没有多大帮助。

解决方案:如果您仍想接收点击或双击事件但请改用MouseDown,请不要在MouseMove中启动D& D:

替换此

private void control_MouseDown(object sender, MouseEventArgs e)
{
    var control = sender as Control;
    this.DoDragDrop(control.Name, DragDropEffects.Move);
}

由此:

private void control_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
        DoDragDrop((sender as Control), DragDropEffects.Move); 
}

别忘了hook up新活动!