C# 自訂拖移視窗控制項

第一種方法

寫成使用者控制項

PS: user32.dll 須使用

using System.Runtime.InteropServices;
  1. 首先在方案總管那裡按右鍵,選擇加入->類別
  2. 新增DragControl.cs
  3. 將底下的程式碼貼到DragControl.cs裡面
  4. 此時在工具箱裡面就可以看到DragControl的控制項了
  5. 把DragControl控制項拉到Form裡面,進入屬性裡面的SelectControl並選擇你要能拖移的控制項
  6. 缺點一個DragControl只能操作一個控制項
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Aria2_Control_Panel
{
    class DragControl : Component
    {
        private Control handleControl;

        public Control SelectControl
        {
            get
            {
                return this.handleControl;
            }
            set
            {
                this.handleControl = value;
                this.handleControl.MouseDown += new MouseEventHandler(this.DragForm_MouseDown);
            }
        }

        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr a, int msg, int wParam, int lParam);
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        private void DragForm_MouseDown(object sender, MouseEventArgs e)
        {
            bool flag = e.Button == MouseButtons.Left;
            if (flag)
            {
                DragControl.ReleaseCapture();
                DragControl.SendMessage(this.SelectControl.FindForm().Handle, 161, 2, 0);
            }
        }
    }
}

第二種方法

寫成方法

1.使用方法:在選擇的物件上設定行為MouseDown
2.並填入Start_MouseDown()

#region 無邊框拖動效果
    [DllImport("user32.dll")]//拖動無窗體的控件
    public static extern bool ReleaseCapture();
    [DllImport("user32.dll")]
    public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
    public const int WM_SYSCOMMAND = 0x0112;
    public const int SC_MOVE = 0xF010;
    public const int HTCAPTION = 0x0002;

    private void Start_MouseDown(object sender, MouseEventArgs e)
    {
        //拖動窗體
        ReleaseCapture();
        SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
    }
#endregion
Last modification:August 27, 2018
If you think my article is useful to you, please feel free to appreciate