Visual studio之C# 重新定义Messbox的显示窗口位置

本文介绍了一种在C#中调整MessageBox显示位置的方法。通过使用FindWindow、GetWindowRect和MoveWindow三个API函数,可以将MessageBox定位到指定坐标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

当前做的APP需要新建一个设置窗口,该设置窗口会出现在靠近屏幕边缘位置,但主窗口铺满屏幕,设置窗口会弹出一些讯息,但默认情况下Messagebox窗口会居中于主窗口,这不太符合要求,正常应该居中于设置窗口,因此此文便是在C#中重新定义Messagebox的显示位置。该方法摘自于codeproject,此处仅仅是做个记录,原文链接会在参考链接中给出。

正文

首先要添加两个命名空间,

using System.Runtime.InteropServices;
using System.Threading;

在窗体类中,添加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

以上Dll,Windows系统中正常情况下均会存在,因此不必要担心Dll不存在的问题,并且任意版本的Framework均支持DllImport参数。

然后定义一个函数用来查找你需要改变位置的Messagebox

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(...)函数前,调用以上函数FindAndMoveMsgBox(...)即可。
此处需要注意的是,由于FindAndMoveMsgBox(...)是通过Title来查找Messagebox,因此,Messagebox.show(...)函数中的Caption参数一定与函数FindAndMoveMsgBox(...)中的title相等。
举例说明,

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

该函数的效果既使CaptionTitleMessagebox,在屏幕的0, 0位置弹出。

至此记录完毕。

参考链接:

记录时间:2017-5-8
记录地点:深圳WZ

转载于:https://www.cnblogs.com/ChYQ/p/6824976.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值