如何让用户在自己选择的位置拖动一个动态创建的控制 [英] How to allow user to drag a dynamically created control at the location of his choice

查看:112
本文介绍了如何让用户在自己选择的位置拖动一个动态创建的控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating an application where I need to generate dynamically created controls say textbox or label etc.

现在我什么用户可以重新定位文本框到他想要的位置。像我们这样在Visual Studio。
的一种方法是使用文本框从他身上得到的值来获得新的位置。但我希望用户界面简单。

Now what I that user can relocate that textbox to his desired location. Like we do in Visual Studio. One way is to get new location by getting values from him using textbox. But I want the user interface easy.

我们能有在的WinForms这样的功能。

Can we have such functionality in winforms

推荐答案

我创建一个简单的表格,演示如何通过拖动控制点动控制。
这个例子假设有一个名为连接到相关的事件处理程序窗体上按钮1按钮。

I have created a simple form that demonstrate how to move the control by dragging the control. The example assumes there is a button named button1 on the form attached to the relevant event handler.

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;
}

这篇关于如何让用户在自己选择的位置拖动一个动态创建的控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆