Excel

Cómo usar VBA para bloquear la PC

¿Alguna vez has necesitado o deseado poder bloquear la PC? ¿Quizás después de ejecutar tu código?

Bueno, ¡es sorprendentemente sencillo de hacer!

Afortunadamente, existe una API sencilla que podemos implementar para realizar todo el trabajo pesado. Todo lo que tenemos que hacer es crear una función contenedora sencilla a su alrededor, como se muestra a continuación:

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


'---------------------------------------------------------------------------------------
' Procedure : LockPC
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : 
' Purpose   : Lock the current PC (this does not logoff the user, simply lock the session)
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - 
' Req'd Refs: None required
' Dependencies: LockWorkStation API Declaration(s)
'
' Usage:
' ~~~~~~
' Call LockPC
'
' ? LockPC
'   Returns -> True  : when successful
'              False : when it fails to lock the PC
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-04-11              Initial Public Release
'                                   Added Function header
'---------------------------------------------------------------------------------------
Public Function LockPC() As Boolean
On Error GoTo Error_Handler
    Dim lRet                  As Long
    
    lRet = LockWorkStation
    If lRet = 0 Then
        Debug.Print "Couldn't lock the PC for an unknown reason."
        Debug.Print Err.LastDllError 'to get more details on the error itself
    Else
        LockPC = True
        Debug.Print "PC Successfully locked!"
    End If
    
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: LockPC" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl  0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Como se muestra en el encabezado de la función, su uso se puede lograr simplemente haciendo lo siguiente:

If LockPC Then
    'Lock PC Call was successful
Else
    'Lock PC Call was NOT successful
End if

O quizás algo más como:

If Not LockPC Then
    Exit Sub
    'Exit Function
End if

Y eso es todo.

Otros recursos sobre el tema

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba