在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");