在C#程序中对MessageBox进行定位的方法

所属分类: 软件编程 / C#教程 阅读数: 46
收藏 0 赞 0 分享

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

更多精彩内容其他人还在看

C# SendInput 模拟鼠标操作的实现方法

C# SendInput 模拟鼠标操作的实现方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#中 paint()与Onpaint()的区别

paint是事件onpaint方法onpaint方法是调用paint事件的,用哪一个,效果是一样,就看那一个方便了内部是这样实现的:
收藏 0 赞 0 分享

c#中GetType()与Typeof()的区别

c#中GetType()与Typeof()的区别,需要的朋友可以参考一下
收藏 0 赞 0 分享

将字符串转换成System.Drawing.Color类型的方法

将字符串转换成System.Drawing.Color类型的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C# 抓取网页内容的方法

C# 抓取网页内容的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于C#后台调用跨域MVC服务及带Cookie验证的实现

本篇文章介绍了,基于C#后台调用跨域MVC服务及带Cookie验证的实现。需要的朋友参考下
收藏 0 赞 0 分享

使用C#获取远程图片 Form用户名与密码Authorization认证的实现

本篇文章介绍了,使用C#获取远程图片 Form用户名与密码Authorization认证的实现。需要的朋友参考下
收藏 0 赞 0 分享

Winform跨线程操作的简单方法

线程间操作无效:从不是创建控件“label1”的线程访问它
收藏 0 赞 0 分享

C# WINFORM 强制让窗体获得焦点的方法代码

C# WINFORM 强制让窗体获得焦点的方法代码,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#中方括号[]的语法及作用介绍

C#中方括号[]可用于数组,索引、属性,更重要的是用于外部DLL类库的引用。
收藏 0 赞 0 分享
查看更多