SendKeys no Windows 7

LEANDRO ALVES

23-05-2012 13:08:58

Pessoal,

Há alguns dias eu venho tentando usar o comando sendKeys no Seven para emular um "Enter" ao pressionar um "Tab". No Windows Xp funciona direitinho, porém no Windows 7 está dando um erro de permissão negada. Eu procurei a respeito na net e encontrei que a partir do Windows Vista este controle foi desabilitado por questão de segurança.
Eu encontrei alguns comandos em API para emular esta rotina porém não consegui adaptar nehum :mrgreen: Primeiro porque são muito complicados, sengundo porque eu nem ao menos consegui indentificar onde é feita a referência para as teclas pressionadas e teclas emuladas.
Eu estou desenvolvendo um aplicativo em VB6 e estou trabalhando com Datagrid. Ele está conectado a uma tabela de dados temporários e ao pressionar Tab ele deve atualizar a tabela e mandar o foco para a próxima célula. Como disse, no XP está funcionando certinho :D , já no Seven :evil: Que coisa!

O Código que estou usando é este:

Código: Selecionar todos

Private Sub DataGrid1_KeyDown(KeyCode As Integer, Shift As Integer)
    
    If KeyCode = 9 And Shift = 0 Then 'TAB
        SendKeys "{Enter}"
        SendKeys "{right}"
    End If
    
    If KeyCode = 9 And Shift = 1 Then 'TAB e Shift pressionado
        SendKeys ("{Enter}")
        SendKeys ("{Left}")
    End If
    
End Sub
Um dos API's que encontrei:

Código: Selecionar todos

Option Explicit

Private Const KEYEVENTF_KEYUP = &H2
Private Const INPUT_KEYBOARD = 1

Private Type KEYBDINPUT
wVk As Integer
wScan As Integer
dwFlags As Long
time As Long
dwExtraInfo As Long
End Type

Private Type GENERALINPUT
dwType As Long
xi(0 To 23) As Byte
End Type

Private Declare Function SendInput Lib "user32.dll" (ByVal nInputs As Long, pInputs As GENERALINPUT, ByVal cbSize As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDst As Any, pSrc As Any, ByVal ByteLen As Long)

Public Function SendKeysA(ByVal vKey As Integer, Optional booDown As Boolean = False)
Dim GInput(0) As GENERALINPUT
Dim KInput As KEYBDINPUT
KInput.wVk = vKey
If Not booDown Then
    KInput.dwFlags = KEYEVENTF_KEYUP
End If
GInput(0).dwType = INPUT_KEYBOARD
CopyMemory GInput(0).xi(0), KInput, Len(KInput)
Call SendInput(1, GInput(0), Len(GInput(0)))
End Function 
Se alguém puder dar uma força aí, eu fico muito grato. :lol:

Abraços

webmaster

24-05-2012 20:04:19

Leandro,

Pesquisei meio na pressa e achei isso:

http://social.technet.microsoft.com/For ... 7ae10dca22

De repente ajuda. Não tive tempo de testar ainda.

Abraços

LEANDRO ALVES

26-05-2012 11:46:08

Bom Dia Tomás,

Muito obrigado pela dica. Através do site que você me indicou eu encontrei este código que é parecido com o que eu postei neste mesmo tópico. O que acontece é que eu não faço a mínima idéia de como usar este procedimento :mrgreen: . Você poderia me orientar em qual local eu menciono a Tecla que desejo e como disparar esta função no evento KeyDown do Datagrid?

Código: Selecionar todos

Option Explicit

' -----------------------------------------------------
' - Module for intercepting calls to VBA.Sendkeys and -
' - using Windows API calls instead to send the keyup -
' - and keydow events                                 -
' -----------------------------------------------------

Private Const USE_MY_SENDKEYS As Boolean = True

Private Declare Sub keybd_event Lib "user32" ( _
    ByVal bVk As Byte, ByVal bScan As Byte, _
    ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
   
Private Const KEYEVENTF_EXTENDEDKEY = &H1
Private Const KEYEVENTF_KEYUP = &H2

Private Declare Function GetVersion Lib "kernel32" () As Long
Private Declare Function VkKeyScan Lib "user32" Alias "VkKeyScanA" ( _
    ByVal cChar As Byte) As Integer
Private Declare Function VkKeyScanW Lib "user32" ( _
    ByVal cChar As Integer) As Integer
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
    lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)

Public Sub KeyDown(ByVal vKey As KeyCodeConstants)
    Call keybd_event(vKey, 0, KEYEVENTF_EXTENDEDKEY, 0)
End Sub

Public Sub KeyUp(ByVal vKey As KeyCodeConstants)
    Call keybd_event(vKey, 0, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
End Sub

Public Function keyCode(ByVal sChar As String) As KeyCodeConstants
    
    Dim bNt As Boolean
    Dim iKeyCode As Integer
    Dim b() As Byte
    Dim iKey As Integer
    Dim vKey As KeyCodeConstants
    Dim iShift As ShiftConstants
    
    ' Determine if we have Unicode support or not:
    bNt = ((GetVersion() And &H80000000) = 0)
    
    ' Get the keyboard scan code for the character:
    If (bNt) Then
        b = sChar
        CopyMemory iKey, b(0), 2
        iKeyCode = VkKeyScanW(iKey)
    Else
        b = StrConv(sChar, vbFromUnicode)
        iKeyCode = VkKeyScan(b(0))
    End If
    
    keyCode = (iKeyCode And &HFF&)
    
End Function

Public Function Sendkeys(ByVal sString As String, _
    Optional ByVal fWait As Boolean = False)

    ' Intercepts the standard SendKeys
    
    Dim key As KeyCodeConstants
    
    If Not USE_MY_SENDKEYS Then
        VBA.Sendkeys sString, fWait
    Else
        Select Case UCase$(sString)
        Case UCase$(SENDKEYS_TAG_BS)
            key = keyCode(Chr(8))
        Case UCase$(SENDKEYS_TAG_DELETE)
            key = keyCode(Chr(127))
        Case UCase$(SENDKEYS_TAG_LEFT)
            key = KeyCodeConstants.vbKeyLeft
        Case UCase$(SENDKEYS_TAG_RIGHT)
            key = KeyCodeConstants.vbKeyRight
        Case UCase$(SENDKEYS_TAG_RETURN)
            key = keyCode(Chr(13))
        Case Else
            key = keyCode(sString)
        End Select
    
        Call KeyDown(key)
        Call KeyUp(key)
        
    End If

End Function
		
Abraços