栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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 , x , y,
      r.Width - r.X ,
      r.Height - r.Y ,
      repaint );
  });
  thr.Start(); /: starts the thread
}

你要在 MessageBox.Show 之前调用这个方法,并确保 caption 参数不能为空,因为 title 参数必须等于 caption 参数。

使用方法:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/124956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号