VB自己设定消息框的显示位置

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

VB自己设定消息框的显示位置

一般来说,无论你使用VB自带的MsgBox还是API函数MessageBox,消息框都会在屏幕的中央弹出。但有时候我们希望它能出现在程序的主窗口附近,这样无论从察看还是操作方面都会给用户带来方便。记得我们前面是怎么找到消息框窗口句柄的吗?既然我们能得到窗口的句柄,就一定能移动它!现在我们就来做一个在程序主窗口居中显示的消息框。

在Module模块中添加以下API函数、类型以及常量的声明:

Public Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect 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

Public 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, "你见过不在屏幕中央的消息框吗?", "改变位置的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, stMsgBoxRect

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) \ 2))

' 这里还要确定消息框的显示位置不会超出屏幕

If xPoint < 0 Then xPoint = 0

If yPoint < 0 Then yPoint = 0

If (xPoint + (stMsgBoxRect.Right - stMsgBoxRect.Left)) > (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

相关文档
最新文档