我是 VBA 新手,因此如果我的問題很愚蠢,請提前原諒。也就是說,我創建了一個非常簡單的點擊按鈕事件,它應該將我的彈出表單移動到螢屏的左上角。我使用的功能是:
Private Sub Command1_Click()
DoCmd.MoveSize(0 ,0)
End Sub
最初它有效,但后來我注意到,如果我的彈出表單位于我的第二臺顯示幕上并使用此功能,它會將彈出表單發送回我的主顯示幕的左上角。有沒有辦法以某種方式告訴函式將表單發送到左上角到打開表單的任何監視器?
由于這不起作用,我嘗試了一個不同的想法,我將使用一個函式來使用表單的“.Move”屬性。我想出了這個:
Private Sub Command1_Click()
Form.Move(0, 0)
End Sub
遺憾的是,這也不起作用,因為“0, 0”坐標似乎與訪問視窗在螢屏上的位置有關,而不是與顯示幕的左上角有關。
這是 Access VBA 的某種限制,還是您認為使用其他技術可行?聽到您對這個問題的看法,我將不勝感激。先感謝您!
uj5u.com熱心網友回復:
雖然這看起來微不足道,但不幸的是,事實并非如此,我們將需要使用大量的 WinAPI。這對初學者來說真的很難。
我們需要幾件事:
- 我們需要能夠確定表單在哪個監視器上
- 我們需要能夠確定該監視器在“虛擬螢屏”中的位置(考慮相對于彼此定位監視器)
- 我們需要能夠以像素為單位確定當前視窗的大小
- 我們需要能夠在“虛擬螢屏”上定位表單。
為此,我們需要幾個宣告。這些最好保存在單獨的模塊中,但如果您 100% 確定它們僅用于此表單,它們也可以用于表單。
一、型別和值宣告:
'https://docs.microsoft.com/en-us/windows/win32/api/windef/ns-windef-rect
Public Type RECT
left As Long
top As Long
right As Long
bottom As Long
End Type
'https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-monitorinfo
Public Type MONITORINFO
cbSize As Long
rcMonitor As RECT
rcWork As RECT
dwFlags As Long
End Type
'Either look this one up by Googling, or create a C program that references winuser.h and print it
Public Const MONITOR_DEFAULTTONEAREST = &H2
然后,函式宣告:
'https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmonitorinfow
Public Declare PtrSafe Function GetMonitorInfoW Lib "User32.dll" (ByVal hMonitor As LongPtr, ByRef lpmi As MONITORINFO) As Boolean
'https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-monitorfromwindow
Public Declare PtrSafe Function MonitorFromWindow Lib "User32.dll" (ByVal hWnd As LongPtr, ByVal dwFlags As Long) As LongPtr
'https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-movewindow
Public Declare PtrSafe Function MoveWindow Lib "User32.dll" (ByVal hWnd As LongPtr, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal bRepaint As Boolean) As Boolean
'https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowrect
Public Declare PtrSafe Function GetWindowRect Lib "User32.dll" (ByVal hWnd As LongPtr, ByRef lpRect As RECT) As Boolean
然后,在表單上,??將其全部投入使用:
Private Sub Command0_Click()
Dim mi As MONITORINFO
Dim monitor As LongPtr
Dim myrect As RECT
'Get the current size and position of the window
GetWindowRect Me.hWnd, myrect
'Determine which monitor it is on
monitor = MonitorFromWindow(Me.hWnd, MONITOR_DEFAULTTONEAREST)
'Make sure WinAPI knows the size of the MONITORINFO struct we're working with
mi.cbSize = LenB(mi)
'Get the monitor info
GetMonitorInfoW monitor, mi
'Move the window to the top right, keep width and height equal to the current values
MoveWindow Me.hWnd, mi.rcMonitor.left, mi.rcMonitor.top, myrect.right - myrect.left, myrect.bottom - myrect.top, True
End Sub
不幸的是,與 相比DoCmd.MoveSize(0 ,0),這要多得多的代碼和更復雜的概念,但我不知道有更簡單的方法。VBA 并不真正支持多顯示幕,因此您通常必須使用 WinAPI 來解決它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/374994.html
