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

作者:goldensun 时间:2022-03-04 18:45:26 

 在 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#,MessageBox
0
投稿

猜你喜欢

  • JDBC连接MySQL并实现模糊查询

    2021-07-06 01:42:28
  • Spring Boot CLI使用教程

    2023-03-30 03:37:02
  • JavaCV实现照片马赛克效果

    2023-04-27 15:55:14
  • hibernate-validator改进校验框架validator v0.4使用

    2023-01-22 21:08:07
  • mybatis 传入null值的解决方案

    2023-11-23 06:54:44
  • openFeign服务之间调用保持请求头信息处理方式

    2022-11-07 23:45:21
  • 如何使用两个栈实现队列Java

    2023-11-29 17:48:09
  • 全面解析SpringBoot文件上传功能

    2023-02-26 15:55:56
  • 10张图总结出并发编程最佳学习路线

    2021-06-03 00:40:16
  • 使用反射方式获取JPA Entity的属性和值

    2023-07-24 17:43:22
  • Java二维数组与稀疏数组相互转换实现详解

    2022-10-28 07:27:33
  • 快速排序算法在Java中的实现

    2022-05-25 01:06:15
  • Java数据结构专题解析之栈和队列的实现

    2022-11-20 01:24:21
  • spring mvc中的@ModelAttribute注解示例介绍

    2023-10-15 07:07:06
  • Spring AOP实现复杂的日志记录操作(自定义注解)

    2023-01-24 15:21:50
  • Spring Cloud项目前后端分离跨域的操作

    2022-05-20 08:11:16
  • 使用spring框架中的组件发送邮件功能说明

    2022-12-29 03:53:55
  • C# 设计模式系列教程-简单工厂模式

    2023-10-31 13:49:29
  • 浅谈Java中各种修饰符与访问修饰符的说明

    2022-10-07 00:49:52
  • Java网络编程之简易聊天室的实现

    2022-05-05 22:23:45
  • asp之家 软件编程 m.aspxhome.com