C++:如何居中MessageBox?
将 Visual Studio C++ 与 MFC 结合使用。如何将 MessageBox 置于其父窗口的中心?目前它以桌面为中心。
Using Visual Studio C++ with MFC. How do I center a MessageBox to it's parent window? Currently it centers to the desktop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要安装一个钩子并在创建时更改对话框位置。
You need to install a hook and change the dialog box position on creation.
::AfxMessageBox() 对我来说出现在 MainFrame 的中心。这基本上是对 ::MessageBox() 的调用,并将 MainFrame 的句柄作为第一个参数。这不适合你吗?
::AfxMessageBox() appears on the center of the MainFrame for me. Which is basically a call to ::MessageBox() with a handle to the MainFrame as the first parameter. Isn't that working for you?
你不能。这就是为什么很多人编写自己的 MessageBox 类的原因。
You can't. That's why a lot of people write their own MessageBox classes.
谁说“不能”?
试试这个:
这是用于 Win32 API,用 C 编写的。根据需要进行翻译...
将其添加到 WndProc 代码中...您可以根据需要设置位置,在本例中,它只是在主程序窗口的中心位置。它将为任何消息框或文件打开/保存对话框以及可能的其他一些本机控件执行此操作。我不确定,但我认为您可能需要包含 COMMCTRL 或 COMMDLG 才能使用它,至少,如果您想要打开/保存对话框,则需要。
我尝试查看 NMHDR 的通知代码和 hwndFrom,然后决定不这样做同样有效,而且更容易。如果您确实想要非常具体,请告诉 FindWindow 查找您为要查找的窗口提供的唯一标题(标题)。
这会在屏幕上绘制消息框之前触发,因此如果您设置一个全局标志来指示代码何时完成操作,并查找唯一的标题,您可以确保您执行的操作只会发生一次(可能会有多个)通知者)。我还没有详细探讨这一点,但我设法让 CreateWindow 在消息框对话框上放置一个编辑框。它看起来就像把老鼠的耳朵移植到克隆猪的脊椎上一样不合时宜,但它确实有效。以这种方式做事可能比自己动手要容易得多。
乌鸦。
编辑:处理 Raymond Chen 提出的问题的小修正。确保父句柄自始至终都一致,这应该可以正常工作。它对我来说确实如此,即使有同一程序的两个实例......
Who said "can't"?
Try this:
This is for Win32 API, written in C. Translate it as you need...
Add that to the WndProc code... You can set position as you like, in this case it just centres over the main program window. It will do this for any messagebox, or file open/save dialog, and likely some other native controls. I'm not sure, but I think you may need to include COMMCTRL or COMMDLG to use this, at least, you will if you want open/save dialogs.
I experimented with looking at the notify codes and hwndFrom of NMHDR, then decided it was just as effective, and far easier, not to. If you really want to be very specific, tell FindWindow to look for a unique caption (title) you give to the window you want it to find.
This fires before the messagebox is drawn onscreen, so if you set a global flag to indicate when action is done by your code, and look for a unique caption, you be sure that actions you take will only occur once (there will likely be multiple notifiers). I haven't explored this in detail, but I managed get CreateWindow to put an edit box on a messagebox dialog. It looked as out of place as a rat's ear grafted onto the spine of a cloned pig, but it works. Doing things this way may be far easier than having to roll your own.
Crow.
EDIT: Small correction to handle the problem raised by Raymond Chen. Make sure that parent handles agree throughout, and this should work ok. It does for me, even with two instances of the same program...