在C#程序中對MessageBox進行定位的方法
更新時間:2015年07月13日 10:54:51 投稿:goldensun
這篇文章主要介紹了在C#程序中對MessageBox進行定位的方法,針對圖形化界面進行調(diào)試,需要的朋友可以參考下
在 C# 中沒有提供方法用來對 MessageBox 進行定位,但是通過 C++ 你可以查找窗口并移動它們,本文講述如何在 C# 中對 MessageBox 進行定位。
首先需在代碼上引入所需名字空間:
using System.Runtime.InteropServices; using System.Threading;
在你的 Form 類里添加如下 DllImport 屬性:
[DllImport("user32.dll")]
static extern IntPtr FindWindow(IntPtr classname, string title); // extern method: FindWindow
[DllImport("user32.dll")]
static extern void MoveWindow(IntPtr hwnd, int X, int Y, int nWidth, int nHeight, bool rePaint); // extern method: MoveWindow
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr hwnd, out Rectangle rect); // extern method: GetWindowRect
接下來就可以查找窗口并移動它:
void FindAndMoveMsgBox(int x, int y, bool repaint, string title)
{
Thread thr = new Thread(() => // create a new thread
{
IntPtr msgBox = IntPtr.Zero;
// while there's no MessageBox, FindWindow returns IntPtr.Zero
while ((msgBox = FindWindow(IntPtr.Zero, title)) == IntPtr.Zero) ;
// after the while loop, msgBox is the handle of your MessageBox
Rectangle r = new Rectangle();
GetWindowRect(msgBox, out r); // Gets the rectangle of the message box
MoveWindow(msgBox /* handle of the message box */, x , y,
r.Width - r.X /* width of originally message box */,
r.Height - r.Y /* height of originally message box */,
repaint /* if true, the message box repaints */);
});
thr.Start(); /: starts the thread
}
你要在 MessageBox.Show 之前調(diào)用這個方法,并確保 caption 參數(shù)不能為空,因為 title 參數(shù)必須等于 caption 參數(shù)。
使用方法:
FindAndMoveMsgBox(0,0,true,"Title");
MessageBox.Show("Message","Title");
相關文章
C#中Abstract方法和Virtual方法的區(qū)別
這篇文章介紹了C#中Abstract方法和Virtual方法的區(qū)別,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-04-04
C# 中使用Stopwatch計時器實現(xiàn)暫停計時繼續(xù)計時功能
這篇文章主要介紹了C# 中使用Stopwatch計時器可暫停計時繼續(xù)計時,主要介紹stopwatch的實例代碼詳解,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03

