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 ;
}
}
{
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!(原代码中的枚举值少了一个关键值。邀月[[email protected]]注)
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 ;
}
}
{
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 ;
}
}
附:
代码下载
代码下载二