日期:2014-06-10  浏览次数:20541 次

【实例说明】
 一般情况下,窗体都包含标题栏、菜单栏、工具栏和状态栏等区域,当拖动窗体时直接在标题栏中按住鼠标左键不放即可实现拖动操作。

 当做浮动窗体时,如果包含窗体边框,那么界面给使用者的感觉将很不友好,因此浮动窗体没有边框,但对于这种没有边框的窗体,该如何进行拖放操作呢?

 本实例将带领读者一起来制作一个拖动无边框窗体的程序。

 

【关键技术】
 本实例实现时主要用到了Windows的两个API函数,即ReleaseCapture和SendMessage,下面分别对它们进行讲解。
 (1)ReleaseCapture函数
    该函数用来释放被当前线程中某个窗口捕获的光标。语法格式如下:

1 [DllImport("user32.dll")]
2 public static extern bool ReleaseCapture();//用来释放被当前线程中某个窗口捕获的光标

说明:程序中使用系统API函数时,首先需要在命名空间区域添加System.Runtime.InteropServices命名空间。

 (2)SendMessage函数
    该函数用来向指定的窗体发送Windows消息。语法格式如下:

1 [DllImport("user32.dll")]
2 public static extern bool SendMessage(IntPtr hwdn,int wMsg,int mParam,int lParam);//向指定的窗体发送Windows消息

注意:详细参数及注释请见文件代码中标注。

【设计过程】
 (1)打开Visual Studio,创建一个WinForm应用程序,命名为DragNoFrameForm。
 (2)更改默认窗体Form1的Name属性为Frm_Main,并将该窗体的FormBorderStyle属性设置为None。
 (3)程序主要代码如下:

 1 using System;
 2 using System.Collections.Generic; 
 3 using System.Linq; 
 4 using System.Windows.Forms;
 5 using System.Runtime.InteropServices;
 6 
 7 namespace DragNoFrameForm
 8 {
 9      public partial class Frm_Main : Form
10      {
11           public Frm_Main()
12           {
13                InitializeComponent();
14           }
15 
16           #region 本程序中用到的API函数
17           [DllImport("user32.dll")]
18           public static extern bool ReleaseCapture();//用来释放被当前线程中某个窗口捕获的光标
19 
20           /// <summary>
21           /// 向指定的窗体发送Windows消息
22           /// </summary>
23           /// <param name="hwdn">表示发送西欧阿西的目的窗口的句柄</param>
24           /// <param name="wMsg">表示被发送的消息</param>
25           /// <param name="mParam">取决于被发送的消息,表示附加的消息信息</param>
26           /// <param name="lParam">取决于被发送的消息,表示附加的消息信息</param>
27           /// <returns>表示处理是否成功</returns>
28           [DllImport("user32.dll")]
29           public static extern bool SendMessage(IntPtr hwdn,int wMsg,int mParam,int lParam);
30           #endregion
31 
32           #region 本程序中需要声明的变量
33           public const int WM_SYSCOMMAND = 0x0112;//该变量表示将向Windows发送的消息类型
34           public const int SC_MOVE = 0xF010;//该变量表示发送消息的附加消息
35           public const int HTCAPTION = 0x0002;//该变量表示发送消息的附加消息
36           #endregion
37 
38           private void ExitContext_Click(object sender, EventArgs e)
39           {
40                Application.Exit();//退出本程序
41           }
42 
43           private void Frm_Main_MouseDown(object sender, MouseEventArgs e)
44           {
45                ReleaseCapture();//用来释放被当前线程中某个窗口捕获的光标
46                SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);//向Windows发送拖动窗体的消息
47           }
48      }
49 }

 

 

 

【来自:http://www.cnblogs.com/LonelyShadow】