现在的位置: 首页 > 综合 > 正文

让MessageBox弹出在当前窗体的中央,而不是在屏幕的中央

2011年01月21日 ⁄ 综合 ⁄ 共 1209字 ⁄ 字号 评论关闭

WinForm中默认的MessageBox默认的弹出位置在屏幕的center,而且没有属性可以修改它,所以在当前活动窗体不在中央时,将会出现,弹出的MessageBox的错位,如下:

邀月工作室

而我们有时需要的是这样:

邀月工作室

昨天看到Codeproject上有一篇文章:《Centering MessageBox, Common DialogBox or Form on applications》,

http://www.codeproject.com/KB/dialog/CenterDialog.aspx

原文的实现原理是:在对话框被打开前,增加了一个WH_CALLWNDPROC hook 来查找WM_INITDIALOG message,其实是一个学习钩子的好示例。

关键代码:

public void WndProcRet(object sender, WndProcRetEventArgs e)
{

switch (e.cw.message)
{
case WndMessage.WM_INITDIALOG:
case WndMessage.WM_UNKNOWINIT:
USER32.MoveWindow(e.cw.hwnd, rect.Left, rect.Top, rect.Width, rect.Height,
1);
// uninstall this hook
WindowsHook wndHook = (WindowsHook)sender;
Debug.Assert(wndProcRetHook
== wndHook);
wndProcRetHook.Uninstall();
wndProcRetHook
= null;
break;
default: break;
}

}

调试时,发现不能实现想要的效果,检查了下代码,增加了一行,OK!(原代码中的枚举值少了一个关键值。邀月[3w@live.cn]注)

public void WndProcRet(object sender, WndProcRetEventArgs e)
{
switch (e.cw.message)
{
case WndMessage.WM_INITDIALOG:
case WndMessage.WM_UNKNOWINIT:
case WndMessage.WM_ACTIVATE://tony 2011.3.12 update 这是能否显示在当前父窗体中央的关键!
USER32.MoveWindow(e.cw.hwnd, rect.Left, rect.Top, rect.Width, rect.Height, 1);
// uninstall this hook
WindowsHook wndHook = (WindowsHook)sender;
Debug.Assert(wndProcRetHook
== wndHook);
wndProcRetHook.Uninstall();
wndProcRetHook
= null;
break;
default: break;
}
}

附:

代码下载
代码下载二

抱歉!评论已关闭.