《VB自己设定消息框的显示位置》由会员分享,可在线阅读,更多相关《VB自己设定消息框的显示位置(3页珍藏版)》请在金锄头文库上搜索。
1、VB自己设定消息框的显示位置VB自己设定消息框的显示位置 一般来说,无论你使用VB自带的MsgBox还是API函数MessageBox,消息框都会在屏幕的中央弹出。但有时候我们希望它能出现在程序的主窗口附近,这样无论从察看还是操作方面都会给用户带来方便。记得我们前面是怎么找到消息框窗口句柄的吗?既然我们能得到窗口的句柄,就一定能移动它!现在我们就来做一个在程序主窗口居中显示的消息框。 在Module模块中添加以下API函数、类型以及常量的声明: Public Declare Function GetWindowRect Lib user32 (ByVal hwnd As Long, lpRec
2、t As RECT) As Long Public Type RECT Left As Long Top As Long Right As Long Bottom As Long End Type Public Declare Function SetWindowPos Lib user32 (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long P
3、ublic Const SWP_NOSIZE As Long = &H1& Public Const SWP_NOZORDER As Long = &H4& Public Const HWND_TOP As Long = 0& 在刚才的窗体上再添加一个Command按钮和一个Timer控件,代码如下: Private Sub Command2_Click 这里我们将自己设置消息框的位置 打开计时器,设定10毫秒后改变消息框的位置 Timer2.Interval = 10 Timer2.Enabled = True 调用 messagebox API 函数 MessageBox Me.hwnd,
4、 你见过不在屏幕中央的消息框吗?, 改变位置的 MessageBox, vbQuestion End Sub Private Sub Timer2_Timer Dim hMsgBox As Long, xPoint As Long, yPoint As Long Dim stMsgBoxRect As RECT, stParentRect As RECT 找到消息框窗口 hMsgBox = FindWindow(#32770, 改变位置的 MessageBox) 如果找到窗口就移动它 If hMsgBox Then 得到消息框和父窗口的矩形位置 GetWindowRect hMsgBox, s
5、tMsgBoxRect GetWindowRect Me.hwnd, stParentRect 计算位置,以便把消息框放到窗体的中央 xPoint = stParentRect.Left + (stParentRect.Right - stParentRect.Left) 2) - (stMsgBoxRect.Right - stMsgBoxRect.Left) 2) yPoint = stParentRect.Top + (stParentRect.Bottom - stParentRect.Top) 2) - (stMsgBoxRect.Bottom - stMsgBoxRect.Top)
6、 2) 这里还要确定消息框的显示位置不会超出屏幕 If xPoint 0 Then xPoint = 0 If yPoint (Screen.Width Screen.TwipsPerPixelX) Then xPoint = (Screen.Width Screen.TwipsPerPixelX) - (stMsgBoxRect.Right - stMsgBoxRect.Left) End If If (yPoint + (stMsgBoxRect.Bottom - stMsgBoxRect.Top) (Screen.Height Screen.TwipsPerPixelY) Then yPoint = (Screen.Height Screen.TwipsPerPixelY) - (stMsgBoxRect.Bottom - stMsgBoxRect.Top) End If 移动位置 SetWindowPos hMsgBox, HWND_TOP, xPoint, yPoint, 0, 0, SWP_NOZORDER Or SWP_NOSIZE End If 关闭计时器 Timer2.Enabled = False End Sub