【问题标题】:How to drag Custom Usercontrol on windows form?如何在 Windows 窗体上拖动自定义用户控件?
【发布时间】:2015-05-01 19:29:03
【问题描述】:

我有一个 sln 文件,其中有两个项目,第一个项目包含一个从 Button 继承的自定义用户控件,第二个项目有一个表单和一个按钮,当我单击表单上的自定义用户控件按钮时一个按钮将被添加到表单中,现在我应该能够在我运行它之后将表单上的按钮拖动到我想要的任何位置,怎么做。

public partial class buttCustom : Button
{
    public buttCustom()
    {
        InitializeComponent();
    }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
        this.Controls.Add(buttControl);
    }
}

我应该能够移动图像中的那个绿色自定义按钮,以便使用鼠标移动到我想要的任何地方。

【问题讨论】:

  • 覆盖MouseMove/MouseDown/MouseUp 事件并在鼠标按下并移到按钮上时移动项目。网上有很多关于如何在表单上拖动控件的教程。
  • 我知道,但是当我单击按钮时如何拖动添加的控件?例如,我将通过单击按钮向表单添加多个控件,然后如何移动它们?
  • 1 和 100 的逻辑相同。
  • 是的,处理按钮的鼠标事件。 “发送者”对象实际上是按钮,您可以将其转换为 buttCustom 对象并修改它的任何属性(如 TopLeftLocation
  • 一个工作示例可以在这里找到codeproject.com/Articles/31840/…

标签: c# .net forms winforms user-controls


【解决方案1】:

我认为您可以在自定义用户控件类中添加以下代码。

[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr one, int two, int three, int four);

private void CustomCtrl_MouseDown(object sender, MouseEventArgs e)
{
    ReleaseCapture();
    SendMessage(Handle, 0x112, 0xf012, 0);
}

所以结果会是这样的:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyViewer.CustomControls
{

    public partial class CustomCtrl : UserControl
    {
        public string formTitleText
        {
            get { return label1.Text; }
            set { label1.Text = value; }
        }
        public CustomCtrl()
        {
            InitializeComponent();
        }

        [DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
        private extern static void ReleaseCapture();
        [DllImport("user32.DLL", EntryPoint = "SendMessage")]
        private extern static void SendMessage(System.IntPtr one, int two, int three, int four);


        // Add MouseDown Event
        private void CustomCtrl_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(Handle, 0x112, 0xf012, 0);
        }
    }
}

然后您可以添加自定义的用户控件,该控件可以从工具箱中拖动到您的表单中。

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多