在C#程序中對(duì)MessageBox進(jìn)行定位的方法
在 C# 中沒(méi)有提供方法用來(lái)對(duì) MessageBox 進(jìn)行定位,但是通過(guò) C++ 你可以查找窗口并移動(dòng)它們,本文講述如何在 C# 中對(duì) MessageBox 進(jìn)行定位。
首先需在代碼上引入所需名字空間:
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
接下來(lái)就可以查找窗口并移動(dòng)它:
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)用這個(gè)方法,并確保 caption 參數(shù)不能為空,因?yàn)?title 參數(shù)必須等于 caption 參數(shù)。
使用方法:
FindAndMoveMsgBox(0,0,true,"Title");
MessageBox.Show("Message","Title");
相關(guān)文章
C#中Abstract方法和Virtual方法的區(qū)別
這篇文章介紹了C#中Abstract方法和Virtual方法的區(qū)別,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
C# 中使用Stopwatch計(jì)時(shí)器實(shí)現(xiàn)暫停計(jì)時(shí)繼續(xù)計(jì)時(shí)功能
這篇文章主要介紹了C# 中使用Stopwatch計(jì)時(shí)器可暫停計(jì)時(shí)繼續(xù)計(jì)時(shí),主要介紹stopwatch的實(shí)例代碼詳解,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03
SQL+C#實(shí)現(xiàn)獲得當(dāng)前月的第一天與最后一天
本文分享了SQL+C#獲得當(dāng)前月的第一天與最后一天的代碼實(shí)例,代碼簡(jiǎn)潔,適合初學(xué)者參考。需要的朋友可以看下2016-12-12
C#實(shí)現(xiàn)簡(jiǎn)易猜數(shù)字游戲
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡(jiǎn)易猜數(shù)字游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
C# PDF Page操作設(shè)置頁(yè)面切換按鈕的方法
這篇文章主要介紹了C# PDF Page操作設(shè)置頁(yè)面切換按鈕的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05

