代码之家  ›  专栏  ›  技术社区  ›  Shantanu Gupta

如何允许用户在其选择的位置拖动动态创建的控件

  •  11
  • Shantanu Gupta  · 技术社区  · 14 年前

    我正在创建一个应用程序,需要在其中生成动态创建的控件,如文本框或标签等。

    现在该用户可以将该文本框重新定位到所需位置。就像在Visual Studio中一样。 一种方法是通过使用文本框从他那里获取值来获取新的位置。但我希望用户界面简单。

    我们能在WinForms中有这样的功能吗

    3 回复  |  直到 6 年前
        1
  •  21
  •   Johann Blais    14 年前

    private Control activeControl;
    private Point previousLocation;
    
    private void button1_Click(object sender, EventArgs e)
    {
        var textbox = new TextBox();
        textbox.Location = new Point(50, 50);
        textbox.MouseDown += new MouseEventHandler(textbox_MouseDown);
        textbox.MouseMove += new MouseEventHandler(textbox_MouseMove);
        textbox.MouseUp += new MouseEventHandler(textbox_MouseUp);
    
        this.Controls.Add(textbox);
    }
    
    void textbox_MouseDown(object sender, MouseEventArgs e)
    {
        activeControl = sender as Control;
        previousLocation = e.Location;
        Cursor = Cursors.Hand;
    }
    
    void textbox_MouseMove(object sender, MouseEventArgs e)
    {
        if (activeControl == null || activeControl != sender)
            return;
    
        var location = activeControl.Location;
        location.Offset(e.Location.X - previousLocation.X, e.Location.Y - previousLocation.Y);
        activeControl.Location = location;
    }
    
    void textbox_MouseUp(object sender, MouseEventArgs e)
    {
        activeControl = null;
        Cursor = Cursors.Default;
    }
    
        2
  •  1
  •   SLaks    14 年前

    DoDragDrop DragDrop

    WM_NCHITTEST DrawToBitmap

        3
  •  1
  •   Zujaj Misbah Khan    6 年前

      private void button1_Click(object sender, EventArgs e)
        {   Point p = new Point(20,70 * i);
            RichTextBox tb = new RichTextBox();
            tb.Location = p;
            tb.Height= 60;
            tb.Width = 100;
            tb.Font = Normal;
            ControlExtension.Draggable(tb,true);
            this.Controls.Add(tb);
            i++;
    

    https://www.nuget.org/packages/Control.Draggable/