在C#程序中對MessageBox進(jìn)行定位的方法
在 C# 中沒有提供方法用來對 MessageBox 進(jìn)行定位,但是通過 C++ 你可以查找窗口并移動(dòng)它們,本文講述如何在 C# 中對 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
接下來就可以查找窗口并移動(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)文章
Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02C# / VB.NET 在PPT中創(chuàng)建、編輯PPT SmartArt圖形的方法詳解
本文介紹通過C#和VB.NET程序代碼來創(chuàng)建和編輯PPT文檔中的SmartArt圖形。文中將分兩個(gè)操作示例來演示創(chuàng)建和編輯結(jié)果,需要的朋友可以參考下2020-10-10C#中ListView控件實(shí)現(xiàn)窗體代碼
這篇文章主要介紹了C#中ListView控件實(shí)現(xiàn)窗體的核心代碼,非常不錯(cuò),具有參考借鑒價(jià)值,對c#listview相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-08-08C#.Net基于正則表達(dá)式抓取百度百家文章列表的方法示例
這篇文章主要介紹了C#.Net基于正則表達(dá)式抓取百度百家文章列表的方法,結(jié)合實(shí)例形式分析了C#獲取百度百家文章內(nèi)容及使用正則表達(dá)式匹配標(biāo)題、內(nèi)容、地址等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08