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

原文的实现原理是:在对话框被打开前,增加了一个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!(原代码中的枚举值少了一个关键值。邀月[[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 ;
}
}

你可能感兴趣的:(让MessageBox弹出在当前窗体的中央,而不是在屏幕的中央)