手机版
你好,游客 登录 注册
背景:
阅读新闻

在 C# 中定位 Windows Forms MessageBox

[日期:2012-10-10] 来源:OSCHINA  作者:红薯 [字体:大 中 小]

在 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 之前调用这个方法,并确保 caption 参数不能为空,因为 title 参数必须等于 caption 参数。

使用方法:

FindAndMoveMsgBox(0,0,true,"Title");
MessageBox.Show("Message","Title");

英文原文,OSCHINA原创翻译

linux
相关资讯       C#  MessageBox 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款