在C#程序中对MessageBox进行定位的方法
在C#中没有提供方法用来对MessageBox进行定位,但是通过C++你可以查找窗口并移动它们,本文讲述如何在C#中对MessageBox进行定位。
首先需在代码上引入所需名字空间:
usingSystem.Runtime.InteropServices; usingSystem.Threading;
在你的Form类里添加如下DllImport属性:
[DllImport("user32.dll")]
staticexternIntPtrFindWindow(IntPtrclassname,stringtitle);//externmethod:FindWindow
[DllImport("user32.dll")]
staticexternvoidMoveWindow(IntPtrhwnd,intX,intY,intnWidth,intnHeight,boolrePaint);//externmethod:MoveWindow
[DllImport("user32.dll")]
staticexternboolGetWindowRect(IntPtrhwnd,outRectanglerect);//externmethod:GetWindowRect
接下来就可以查找窗口并移动它:
voidFindAndMoveMsgBox(intx,inty,boolrepaint,stringtitle)
{
Threadthr=newThread(()=>//createanewthread
{
IntPtrmsgBox=IntPtr.Zero;
//whilethere'snoMessageBox,FindWindowreturnsIntPtr.Zero
while((msgBox=FindWindow(IntPtr.Zero,title))==IntPtr.Zero);
//afterthewhileloop,msgBoxisthehandleofyourMessageBox
Rectangler=newRectangle();
GetWindowRect(msgBox,outr);//Getstherectangleofthemessagebox
MoveWindow(msgBox/*handleofthemessagebox*/,x,y,
r.Width-r.X/*widthoforiginallymessagebox*/,
r.Height-r.Y/*heightoforiginallymessagebox*/,
repaint/*iftrue,themessageboxrepaints*/);
});
thr.Start();/:startsthethread
}
你要在MessageBox.Show之前调用这个方法,并确保caption参数不能为空,因为title参数必须等于caption参数。
使用方法:
FindAndMoveMsgBox(0,0,true,"Title");
MessageBox.Show("Message","Title");
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短