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

背景

当前做的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

posted @ 2017-05-08 14:35  Ch_Y_Q  阅读(2975)  评论(0编辑  收藏  举报