窗體標題欄外的拖動操作
2024-07-21 02:16:24
供稿:網(wǎng)友
窗體標題欄外的拖動操作
(作者:張均洪) 2004-9-3
我們知道對窗體的拖動只需要點住標題欄,拖動鼠標就可以了.但有些時候我們想在窗體的標題欄外的區(qū)域?qū)嵭型蟿哟绑w的操作.這時就要需要我們自已寫些代碼了,下面是我的做法,供大家參觀.
新建一個窗體form1,并放入兩個radiobutton控件,第一個是確定是否窗體拖動,第三個是確定是否指定某一區(qū)域進行窗體拖動.
以下是窗體代碼:
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; //鼠標是不是按下了
//指定一個區(qū)域,好寫字在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指定的區(qū)域內(nèi)
//那么我們同意移動窗體操作哈。
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的區(qū)域,筆的顏色是紅的哈
e.graphics.fillrectangle(b, _rec);
//改變筆的顏色
b.color = color.white;
//重新定義一個區(qū)域,這個區(qū)域其實就是_rec變量的區(qū)域
rectanglef recf = new rectanglef(_rec.x,
_rec.y,
_rec.width,
_rec.height);
//在這個區(qū)域?qū)憥讉€字呢
e.graphics.drawstring("click on me drag", font, b, recf);
}
else
{
//如果不同意用區(qū)域改變窗體位置,就把背景設為窗體的
//顏色,免得影響視覺。
b.color = backcolor;
//把這個區(qū)域涂了
e.graphics.fillrectangle(b, _rec);
}
b.dispose();//把筆丟了,免得占我地方
}
private void radiobutton2_checkedchanged(object sender, eventargs e)
{
this.invalidate(this._rec);//使_rec指定的地方無效了
}
}
}