WinForm 无边框窗体 拖动工作区移动窗体

方案1 通过重载消息处理实现。重写窗口过程(WndProc),处理一些非客户区消息(WM_NCxxxx),C#中重写窗口过程不用再调用SetWindowLong API了,直接overide一个WndProc就可以了,不用声明api函数。

鼠标的拖动只对窗体本身有效,不能在窗体上的控件区域点击拖动

  1. protected override void WndProc(ref Message m)  
  2.         {  
  3.             base.WndProc(ref m);  
  4.             if (m.Msg == 0x84)  
  5.             {  
  6.                 switch (m.Result.ToInt32())  
  7.                 {  
  8.                     case 1:  
  9.                         m.Result = new IntPtr(2);  
  10.                         break;  
  11.                 }  
  12.             }  
  13.         }  

方案2 调用非托管的动态链接库,通过控件的鼠标按下事件(MouseDown)发送一个拖动的消息,可以给控件添加MouseDown事件后,拖动这个控件来移动窗体

  1. using System.Runtime.InteropServices;  
  2. [DllImport("User32.DLL")]  
  3. public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);  
  4. [DllImport("User32.DLL")]  
  5. public static extern bool ReleaseCapture();  
  6. public const uint WM_SYSCOMMAND = 0x0112;  
  7. public const int SC_MOVE = 61456;  
  8. public const int HTCAPTION = 2;  
  9. private void Form1_MouseDown(object sender, MouseEventArgs e)  
  10. {  
  11.     ReleaseCapture();  
  12.     SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);  
  13. }  

方案3 直接在控件上写事件,朋友的是一个PictureBox 停靠在主窗体,然后主窗体设置的无边框,用的是这中方法

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. namespace TestShow  
  9. {  
  10.     public partial class Form1 : Form  
  11.     {  
  12.         public Form1()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.         Point downPoint;  
  17.         private void pictureBox1_MouseDown(object sender, MouseEventArgs e)  
  18.         {  
  19.             downPoint = new Point(e.X, e.Y);  
  20.         }  
  21.         private void pictureBox1_MouseMove(object sender, MouseEventArgs e)  
  22.         {  
  23.             if (e.Button == MouseButtons.Left)  
  24.             {  
  25.                 this.Location = new Point(this.Location.X + e.X - downPoint.X,  
  26.                     this.Location.Y + e.Y - downPoint.Y);  
  27.             }  
  28.         }  
  29.     }  

原文地址:https://www.cnblogs.com/ylsoo/p/2866171.html