下面的示例代码说明如何使 Microsoft Excel“总在前面”。这可以防止其他应用程序显示在 Microsoft Excel 前面。
Option Explicit Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As Long Private 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 Global Const HWND_TOPMOST = -1 Global Const HWND_NOTOPMOST = -2
Sub SetOnTop() Dim WinHnd As Long, SUCCESS As Long WinHnd = FindWindow("xlmain", Application.Caption) '如若要设置程序为access,请将ClassName "xlmain" 改为 "Omain" 即可。
SUCCESS = SetWindowPos(WinHnd, HWND_TOPMOST, 0, 0, 0, 0, Flags) '下面一行只是为了 20 秒之后将 Excel 切换回正常操作状态 Application.OnTime Now + TimeValue("00:00:20"), "NotOnTop" End Sub
Sub NotOnTop() Dim WinHnd As Long, SUCCESS As Long WinHnd = FindWindow("xlmain", Application.Caption) SUCCESS = SetWindowPos(WinHnd, HWND_NOTOPMOST, 0, 0, 0, 0, Flags) End Sub