窗体标题栏外的拖动操作
我们知道对窗体的拖动只需要点住标题栏,拖动鼠标就可以了.但有些时候我们想在窗体的标题栏外的区域实行拖动窗体的操作.这时就要需要我们自已写些代码了,下面是我的做法,供大家参观.
新建一个窗体form1,并放入两个radiobutton控件,第一个是确定是否窗体拖动,第三个是确定是否指定某一区域进行窗体拖动.
以下是窗体代码:
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.windows.forms; using system.io;
namespace windowsapplication1 { partial class form1 : form { point _startxy; //鼠标按下的位置 bool _movedown=false; //鼠标是不是按下了 //指定一个区域,好写字在onpaint中 rectangle _rec = new rectangle(50, 50, 70, 70); public form1() { initializecomponent(); }
protected override void onmousedown(mouseeventargs e) { //要移动吗?由按下鼠标(onmousedown)确定哈 bool oktomove=false; base.onmousedown(e);
if(this.radiobutton1.checked) { oktomove=true; } else { //如果按下鼠标的点坐标在_rec指定的区域内 //那么我们同意移动窗体操作哈。 if(this._rec.contains(this.pointtoclient(mouseposition))) { oktomove = true;
} } //如果同意移动,就把按下鼠标一瞬的坐标给_startxy //并同意按着鼠标移动。 if(oktomove==true) { //把当前的鼠标位置赋给变量 _startxy = mouseposition; _movedown = true; } }
protected override void onmousemove(mouseeventargs e) { base.onmousemove(e); //如果同意按着鼠标移动,就把移动的量给变量 //以便窗体按你的量移动。 if (_movedown) { int xdiff,ydiff; xdiff = mouseposition.x - _startxy.x; ydiff = mouseposition.y - _startxy.y; //改变窗体位置 this.left = this.left + xdiff; this.top = this.top + ydiff; //把新位置给_startxy变量了哈 _startxy = mouseposition; } }
protected override void onmouseup(mouseeventargs e) { base.onmouseup(e); _movedown = false;
}
protected override void onpaint(painteventargs e) { base.onpaint(e); //要一支新画笔,向net要哈 solidbrush b = new solidbrush(color.red); if (radiobutton2.checked) { //填充_rec的区域,笔的颜色是红的哈 e.graphics.fillrectangle(b, _rec); //改变笔的颜色 b.color = color.white; //重新定义一个区域,这个区域其实就是_rec变量的区域 rectanglef recf = new rectanglef(_rec.x, _rec.y, _rec.width, _rec.height); //在这个区域写几个字呢 e.graphics.drawstring("click on me drag", font, b, recf); } else { //如果不同意用区域改变窗体位置,就把背景设为窗体的 //颜色,免得影响视觉。 b.color = backcolor; //把这个区域涂了 e.graphics.fillrectangle(b, _rec); } b.dispose();//把笔丢了,免得占我地方 }
private void radiobutton2_checkedchanged(object sender, eventargs e) { this.invalidate(this._rec);//使_rec指定的地方无效了 }
} } |