确定计算机是否被锁定

Determine if the computer is locked

我有一个宏,可以在弹出会议通知时从 Outlook 向我发送一条文本。如果我不在我的电脑前,我想想办法只制作该宏 运行。我一直在寻找一种方法来从 Skype for Business 中提取我的状态,确定 PC 是否已锁定,并查看是否插入了智能卡。一切都没有太多运气。寻找适用于 VBA 的简单解决方案。

也许这对您有帮助

Option Explicit

Private Declare Function SwitchDesktop Lib "User32" (ByVal hDesktop As Long) As Long
Private Declare Function OpenDesktop Lib "User32" Alias "OpenDesktopA" (ByVal lpszDesktop As String, ByVal dwFlags As Long, ByVal fInherit As Long, ByVal dwDesiredAccess As Long) As Long
Private Declare Function CloseDesktop Lib "User32" (ByVal hDesktop As Long) As Long

Private Const DESKTOP_SWITCHDESKTOP As Long = &H100    

Function desktopLocked() As String
Dim p_lngHwnd As Long
Dim p_lngRtn As Long
Dim p_lngErr As Long
Dim System As String

    p_lngHwnd = OpenDesktop(lpszDesktop:="Default", dwFlags:=0, fInherit:=False, dwDesiredAccess:=DESKTOP_SWITCHDESKTOP)

    If p_lngHwnd = 0 Then
        System = "Error"
    Else
        p_lngRtn = SwitchDesktop(hDesktop:=p_lngHwnd)
        p_lngErr = Err.LastDllError

        If p_lngRtn = 0 Then
            If p_lngErr = 0 Then
                System = "Locked"
            Else
                System = "Error"
            End If
        Else
            System = "Unlocked"
        End If

        p_lngHwnd = CloseDesktop(p_lngHwnd)
    End If
    desktopLocked = System
End Function

更新:示例如何使用上面的函数

Option Explicit
#If VBA7 Then
Declare PtrSafe Function LockWorkStation Lib "user32.dll" () As Long
#Else
Declare Function LockWorkStation Lib "user32.dll" () As Long
#End If

Dim iTimerSet As Double

Public Sub SaveAndClose()
    If desktopLocked = "Locked" Then
        ThisWorkbook.Close True
    Else
        iTimerSet = Now + TimeValue("00:00:03")
        Application.OnTime iTimerSet, "SaveAndClose"
    End If

End Sub

Sub LockPC()
    SaveAndClose
    LockWorkStation
End Sub

只需 运行 LockPC 并等待 3 秒,然后解锁工作站。文件已同时关闭。

我使用了这里的代码

Function IsProcessRunning(process As String)
    Dim objList As Object

    Set objList = GetObject("winmgmts:") _
        .ExecQuery("select * from win32_process where name='" & process & "'")

    If objList.Count > 0 Then
        IsProcessRunning = True
    Else
        IsProcessRunning = False
    End If

End Function

基于这里的回答In Python 3, how can I tell if Windows is locked?

我打电话给

IsProcessRunning("LogonUI.exe")

它似乎有效。