C#窗体 隐藏标题栏后 移动窗口的方法

在窗口程序的开发中,我们经常会需要当用户鼠标点击窗口的任何地方时,能够让窗口随鼠标一起移动。特别是当你的WinForms窗口没有窗口栏(Form.FormBorderStyle = None),用户无法通过点击窗口栏移动窗口时,这种实现就很必要了。
应该有很多方法可以实现,这里介绍两种方法:一种方法就是自己编程实现窗口的位置随鼠标改变;另一种就是直接利用Windows的API。

设计一个窗体时,把以下代码加入到窗口中,就可以实现这个功能:

 1  private   bool  IsMouseDownInForm  =   false ;
 2  private  Point p;
 3  private   void  Form1_MouseDown( object  sender, MouseEventArgs e)
 4  {
 5    IsMouseDownInForm  =   true ;
 6    p  =  e.Location;
 7  }
 8  private   void  Form1_MouseUp( object  sender, MouseEventArgs e)
 9  {
10    IsMouseDownInForm  =   false ;
11  }
12  private   void  Form1_MouseMove( object  sender, MouseEventArgs e)
13  {
14     if  (IsMouseDownInForm)
15    {
16      Left  +=  e.Location.X  -  p.X;
17      Top  +=  e.Location.Y  -  p.Y;
18    }
19  }

或者
 1  private  Point mouse_offset;
 2  private   void  Form1_MouseDown( object  sender, MouseEventArgs e)
 3  {
 4    mouse_offset  =   new  Point( - e.X,  - e.Y); 
 5  }
 6 
 7  private   void  Form1_MouseMove( object  sender, MouseEventArgs e)
 8  {
 9     if  (e.Button  ==  MouseButtons.Left)
10    {
11      Point mousePos  =  Control.MousePosition;
12      mousePos.Offset(mouse_offset.X, mouse_offset.Y);
13      Location  =  mousePos;
14    }
15  }

当然,也可以设计一个窗口基类,override Form的OnMouseMove、OnMouseUp、OnMouseDown方法,实现这个小功能。

第二种方法是利用Windows的API,熟悉Windows API编程的人应该很容易就理解了。
首先,利用平台调用,引入User32.dll中以下两个函数的调用:
 1  using  System.Runtime.InteropServices;
 2  public   const   int  WM_NCLBUTTONDOWN  =   0xa1 ;
 3  public   const   int  HT_CAPTION  =   0x2 ;
 4  [DllImportAttribute( " user32.dll " )]
 5  public   static   extern   int  SendMessage(IntPtr hWnd,  int  Msg,  int  wParam,  int  lParam);
 6  [DllImportAttribute( " user32.dll " )]
 7  public   static   extern   bool  ReleaseCapture();
 8  然后,你只需要在窗口的MouseDown事件处理中加入以下代码就可以了:
 9  private   void  Form1_MouseDown( object  sender, System.Windows.Forms.MouseEventArgs e)
10 
11     if  (e.Button  ==  MouseButtons.Left)
12    {
13      ReleaseCapture();
14      SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION,  0 );
15    }
16 


转载于:https://www.cnblogs.com/uhome/archive/2011/06/02/2067668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值