欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-20 22:10:40
 在 c# 中没有提供方法用来对 messagebox 进行定位,但是通过 c++ 你可以查找窗口并移动它们,本文讲述如何在 c# 中对 messagebox 进...

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