使用Autoexec宏来自动操作一个或多个ACCESS数据库,特别是如果开发者试图获Access对象模型(Access Object Model),胜过使用Jet引擎(能通过DAO和ADO来获取的)。不管怎样,Access不提供任何内置的方法来有条件避开这个Autoexec宏。如果数据库包括了这个宏,一打开就会运行。当未设置数据库的AllowBypassKey属性时,可以在启动数据库时按住Shift键来避开运行这个宏。
如果没有设置AllowBypassKey属性,那么可以通过编程方式模拟启动数据库时按住Shift键,这样可以自动避开数据库启动的自动代码。通过引用隐藏的ACCESS数据库实例来避开数据库的自动宏,你可以使用下面的函数fGetRefNoAutoexec。
'********* Code Start ***********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
Private Declare Function SetKeyboardState _
Lib "user32" _
(lppbKeyState As Any) _
As Long
Private Declare Function GetKeyboardState _
Lib "user32" (pbKeyState As Any) _
As Long
Private Declare Function GetWindowThreadProcessId _
Lib "user32" _
(ByVal hWnd As Long, _
lpdwProcessId As Long) _
As Long
Private Declare Function AttachThreadInput _
Lib "user32" _
(ByVal idAttach As Long, _
ByVal idAttachTo As Long, _
ByVal fAttach As Long) _
As Long
Private Declare Function SetForegroundWindow _
Lib "user32" _
(ByVal hWnd As Long) _
As Long
Private Declare Function SetFocusAPI _
Lib "user32" Alias "SetFocus" _
(ByVal hWnd As Long) _
As Long
Private Const VK_SHIFT = &H10
Private Const VK_LSHIFT = &HA0
Private Const VK_RSHIFT = &HA1
Function fGetRefNoAutoexec( _
ByVal strMDBPath As String) _
As Access.Application
On Error GoTo ErrHandler
Dim objAcc As Access.Application
Dim TIdSrc As Long, TIdDest As Long
Dim abytCodesSrc(0 To 255) As Byte
Dim abytCodesDest(0 To 255) As Byte
If (Len(Dir$(strMDBPath, vbNormal)) = 0) Then
Err.Raise 53
End If
Set objAcc = New Access.Application
With objAcc
.Visible = True
' attach to process
TIdSrc = GetWindowThreadProcessId( _
Application.hWndAccessApp, ByVal 0)
TIdDest = GetWindowThreadProcessId( _
.hWndAccessApp, ByVal 0)
If CBool(AttachThreadInput(TIdSrc, TIdDest, True)) Then
Call SetForegroundWindow(.hWndAccessApp)
Call SetFocusAPI(.hWndAccessApp)
' 设置Shift状态
Call GetKeyboardState(abytCodesSrc(0))
Call GetKeyboardState(abytCodesDest(0))
abytCodesDest(VK_SHIFT) = 128
Call SetKeyboardState(abytCodesDest(0))
' 打开一个带有Autoexec宏的mdb
Call .OpenCurrentDatabase(strMDBPath, False)
' 恢复键盘状态
Call SetKeyboardState(abytCodesSrc(0))
End If
' release
Call AttachThreadInput(TIdSrc, TIdDest, False)
Call SetForegroundWindow(Application.hWndAccessApp)
Call SetFocusAPI(Application.hWndAccessApp)
End With
Set fGetRefNoAutoexec = objAcc
Set objAcc = Nothing
Exit Function
ErrHandler:
If (TIdDest) Then Call AttachThreadInput(TIdSrc, TIdDest, False)
Call SetForegroundWindow(Application.hWndAccessApp)
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Function
'********* Code End *********** |