• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#递归拷贝文件夹下文件以及文件夹发布时间:2022-07-13
下一篇:
c# 爬虫(二) 模拟登录 c# 爬虫(一) HELLO WORLD发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap