c# 移动窗体和控件

在winform程序里面,有时候我们需要移动没有标题栏窗体或是窗体内的控件,用几个事件如鼠标单击,移动,等再加上坐标的计算可以完成这一功能,但是最近发现了一个API函数,可以非常简单方便的完成这个功能。如下:

       

ExpandedBlockStart.gif 代码
[DllImportAttribute( " user32.dll " )]
        
private   extern   static   bool  ReleaseCapture();
        [DllImportAttribute(
" user32.dll " )]
        
private   extern   static   int  SendMessage(IntPtr handle,  int  m,  int  p,  int  h);

 

在使用这两个函数时就导入using System.Runtime.InteropServices;

如下使用:

      ReleaseCapture();
                SendMessage(this.Handle, 0xA1, 0x2, 0);

这里面除this.Handle参数外其它的不需改变。例如我们给窗体定义一个MouseDown事件:

this.MouseDown += new MouseEventHandler(MyBaseControl_MouseDown);

那么就可以在点击窗体的任何一点而进行拖动操作。事件内代码如:

ExpandedBlockStart.gif 代码
 1  protected   void  MyBaseControl_MouseDown( object  sender, MouseEventArgs e)
 2          {
 3               if  (e.Button  ==  MouseButtons.Left )
 4              {
 5                   this .Cursor  =  Cursors.SizeAll;
 6                  ReleaseCapture();
 7                  SendMessage( this .Handle,  0xA1 0x2 0 );
 8                   this .Cursor  =  Cursors.Default;
 9              }
10          }
11 

 

如果用于运行时的某个控件,则可以把上面的代码放入此控件的MouseDown事件中,只是SendMessage(this.Handle, 0xA10x20);中的

this.Handle参数应改为此控件的Handle,如this.button1.Handle即可实现。

转载于:https://www.cnblogs.com/aidydream/archive/2010/03/05/1679247.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值