Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 17
  1. #1
    Utente di HTML.it L'avatar di mvent
    Registrato dal
    Jun 2002
    Messaggi
    230

    [vb net/2012] GetAsyncKeyState: annullare il tasto premuto

    Ho fatto un po' di ricerche nella rete ma non ho capito bene.

    Allora: con l'API GetAsyncKeyState riesco a sapere ogni volta che l'utente preme un tasto, anche i tasti speciali tipo CTRL, ALT, CANC, tasto Windows, eccetera.
    Ho provato e funziona.

    Ma se ho la necessità di annullare/ignorare i tasti speciali premuti, come faccio? Devo usare le librerie hook? Sono piuttosto difficili per quello che ho visto...

    La mia necessità è semplicemente questa: se l'utente preme ALT, CTRL, tasto WINDOWS, oppure CTRL+ESC, ALT+TAB, CTRL+ALT+CANC, devo impedire le conseguenze della pressione di questi tasti: l'utente deve stare sul mio form e deve uscire solo come dico io.

  2. #2
    Utente di HTML.it L'avatar di mvent
    Registrato dal
    Jun 2002
    Messaggi
    230
    Ecco, ho trovato anche questa funzione, da mettere sul form:

    codice:
     Protected Overrides Function ProcessCmdKey _
           (ByRef msg As System.Windows.Forms.Message, _
            ByVal keyData As System.Windows.Forms.Keys) As Boolean
    
            '********************************************************
            'DA COMMENTARE IN RELEASE
            'questo:
            MsgBox(keyData & " " & keyData.ToString)
            'in fase di debug scrive nell'output le informazioni
            'sul tasto premuto, serve per identificare il valore 
            '"keydata" da inserire nella lista.
            '********************************************************
    
            If keyData = 262162 Then msg = Nothing 'tasto ALT
            If keyData = 262162 Then keyData = 0 'tasto ALT
          
      If keyData = 115 Then keyData = 0 'tasto F4
      If keyData = 115 Then msg = Nothing 'tasto F4
    
            Return MyBase.ProcessCmdKey(msg, keyData)
    
        End Function
    riesce ad intercettare tutti i tasti ma ho provato a annullare le due variabili nel caso di pressione di ALT e di F4 e non funziona...


  3. #3
    Utente di HTML.it L'avatar di mvent
    Registrato dal
    Jun 2002
    Messaggi
    230
    Dato che al primo messaggio ho parlato delle "librerie hook", metto qui di seguito un esempio di quello a cui facevo riferimento.
    A quanto pare - comunque - la combinazione CTRL+ALT+CANC non viene bloccata neanche con questo metodo e infatti il programmatore che ha fatto il codice seguente ha previsto una procedura per chiudere il task manager.

    VB.NET - Disabilitare o Intercettare i tasti speciali di Windows (Codice)
    Link
    Oggi vi voglio mettere a disposizione una funzione che ho trovato su internet, che serve per intercettare i tasti speciali di Windows da codice VB.NET . Blocca i tasti CTRL+ESC , ALT+TAB, ALT+F4, uccide il processo TaskMenager quando si fà CTRL + ALT + CANC . Premetto che questo codice è rivelato dagli AntiVirus come probabile Virus e pertanto lo metto a disposizione solo per scopo informativo, quindi non mi assumo nessuna responsabilità sull'uso che ne fate. Dovete creare un file Modulo ed inserire il seguente codice e lo salvate Keyboard.vb : CODICE VISUAL STUDIO 2010 - VISUAL BASIC .NET - VB.NET:
    codice:
    Imports System.Runtime.InteropServices
    Imports System.Reflection
    Imports System.Drawing
    Imports System.Threading
    Module Keyboard
    
        <DllImport("kernel32.dll", CharSet:=CharSet.Auto)> _
        Public Function GetModuleHandle(ByVal lpModuleName As String) As IntPtr
        End Function
        Public Declare Function UnhookWindowsHookEx Lib "user32" _
          (ByVal hHook As Integer) As Integer
        Public Declare Function SetWindowsHookEx Lib "user32" _
          Alias "SetWindowsHookExA" (ByVal idHook As Integer, _
          ByVal lpfn As KeyboardHookDelegate, ByVal hmod As IntPtr, _
          ByVal dwThreadId As Integer) As Integer
        Private Declare Function GetAsyncKeyState Lib "user32" _
          (ByVal vKey As Integer) As Integer
        Private Declare Function CallNextHookEx Lib "user32" _
          (ByVal hHook As Integer, _
          ByVal nCode As Integer, _
          ByVal wParam As Integer, _
          ByVal lParam As KBDLLHOOKSTRUCT) As Integer
        Public Structure KBDLLHOOKSTRUCT
            Public vkCode As Integer
            Public scanCode As Integer
            Public flags As Integer
            Public time As Integer
            Public dwExtraInfo As Integer
        End Structure
        ' Low-Level Keyboard Constants
        Private Const HC_ACTION As Integer = 0
        Private Const LLKHF_EXTENDED As Integer = &H1
        Private Const LLKHF_INJECTED As Integer = &H10
        Private Const LLKHF_ALTDOWN As Integer = &H20
        Private Const LLKHF_UP As Integer = &H80
        ' Virtual Keys
        Public Const VK_TAB As Integer = &H9
        Public Const VK_CONTROL As Integer = &H11
        Public Const VK_ESCAPE As Integer = &H1B
        Public Const VK_DELETE As Integer = &H2E
        Private Const WH_KEYBOARD_LL As Integer = 13
        Public KeyboardHandle As Integer
        ' Implement this function to block as many
        ' key combinations as you'd like
        Public Function IsHooked( _
          ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean
            Debug.WriteLine("Hookstruct.vkCode: " & Hookstruct.vkCode)
            Debug.WriteLine(Hookstruct.vkCode = VK_ESCAPE)
            Debug.WriteLine(Hookstruct.vkCode = VK_TAB)
            'MessageBox.Show(Hookstruct.vkCode.ToString)
            If (Hookstruct.vkCode = VK_ESCAPE) And _
              CBool(GetAsyncKeyState(VK_CONTROL) _
              And &H8000) Then
                Call HookedState("Ctrl + Esc blocked")
                Return True
            End If
            If (Hookstruct.vkCode = VK_TAB) And _
              CBool(Hookstruct.flags And _
              LLKHF_ALTDOWN) Then
                Call HookedState("Alt + Tab blockd")
                Return True
            End If
            If (Hookstruct.vkCode = VK_ESCAPE) And _
              CBool(Hookstruct.flags And _
                LLKHF_ALTDOWN) Then
                Call HookedState("Alt + Escape blocked")
                Return True
            End If
            '' disable PrintScreen here
            If (Hookstruct.vkCode = 44) Then
                Call HookedState("Print blocked")
                Return True
            End If
            Return False
        End Function
        Private Sub HookedState(ByVal Text As String)
            Debug.WriteLine(Text)
        End Sub
        Public Function KeyboardCallback(ByVal Code As Integer, _
          ByVal wParam As Integer, _
          ByRef lParam As KBDLLHOOKSTRUCT) As Integer
            If (Code = HC_ACTION) Then
                Debug.WriteLine("Calling IsHooked")
                If (IsHooked(lParam)) Then
                    Return 1
                End If
            End If
            Return CallNextHookEx(KeyboardHandle, _
              Code, wParam, lParam)
        End Function
        Public Delegate Function KeyboardHookDelegate( _
          ByVal Code As Integer, _
          ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) _
                       As Integer
        <MarshalAs(UnmanagedType.FunctionPtr)> _
        Private callback As KeyboardHookDelegate
        Public Sub HookKeyboard(ByRef f As Form)
            callback = New KeyboardHookDelegate(AddressOf KeyboardCallback)
            KeyboardHandle = SetWindowsHookEx(WH_KEYBOARD_LL, callback, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0)
            'MessageBox.Show(KeyboardHandle.ToString)
            Call CheckHooked()
        End Sub
        Public Sub CheckHooked()
            If (Hooked()) Then
                Debug.WriteLine("Keyboard hooked")
            Else
                Debug.WriteLine("Keyboard hook failed: " & Err.LastDllError)
            End If
        End Sub
        Private Function Hooked() As Boolean
            Hooked = KeyboardHandle <> 0
        End Function
        Public Sub UnhookKeyboard()
            If (Hooked()) Then
                Call UnhookWindowsHookEx(KeyboardHandle)
            End If
        End Sub
    End Module
    
    Come invocare le funzioni da un From di Windows con due bottoni , copiate il seguente codice.
    
    CODICE VISUAL STUDIO 2010 - VISUAL BASIC .NET - VB.NET:
    
    Imports System.Runtime.InteropServices
    Imports System.Reflection
    Imports System.Drawing
    Imports System.Threading
    Public Class Form1
        Dim MyThread As Threading.Thread
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Keyboard.HookKeyboard(Me)
        End Sub
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Keyboard.UnhookKeyboard()
        End Sub
    
    
        Public Sub KillProcess(ByRef strProcessToKill As String)
            Dim proc() As Process = Process.GetProcesses
            For i As Integer = 0 To proc.GetUpperBound(0)
                If proc(i).ProcessName = strProcessToKill Then
                    proc(i).Kill()
                End If
            Next
        End Sub
    
        Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
            MyThread.Abort()
        End Sub
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
           'Questo serve per evitare di far apparire la Task Menager quando si fà Control + Alt + Canc
            MyThread = New Threading.Thread(AddressOf  UccidiTakManager)
            MyThread.Start()
        End Sub
    
        Private Sub UccidiTakManager()
            Do While True
                KillProcess("taskmgr")
                Threading.Thread.Sleep(10)
            Loop
        End Sub
    End Class
    La mia domanda rimane: non esiste un metodo più semplice per bloccare i tasti CTRL, ALT, F4, TAB e loro combinazioni?

  4. #4
    Utente di HTML.it L'avatar di oregon
    Registrato dal
    Jul 2005
    residenza
    Roma
    Messaggi
    36,480
    No ... mi sa di no.

    E per il CTRL-ALT-CANC è impossibile.
    No MP tecnici (non rispondo nemmeno!), usa il forum.

  5. #5
    Utente di HTML.it L'avatar di mvent
    Registrato dal
    Jun 2002
    Messaggi
    230
    Originariamente inviato da oregon
    No ... mi sa di no.

    E per il CTRL-ALT-CANC è impossibile.
    Va bè, alla fin fine chiudere il task manager non credo sia un problema. E' sufficiente mettere un oggetto Timer e controllare ogni X secondi se l'exe è aperto e eventualmente chiuderlo.
    Di solito con gli altri exe funziona, penso che non ci dovrebbero essere problemi.

    Esempio 1:
    codice:
    Dim PrcProcesso As System.Diagnostics.Process()  
    
    PrcProcesso = Process.GetProcessesByName("taskmgr")
    If (PrcProcesso.Length > 0) Then
          PrcProcesso(0).Kill()
    OPPURE (?) PrcProcesso(0).CloseMainWindow()
    
          System.Threading.Thread.Sleep(300)
    End If
    Esempio 2:
    codice:
    Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As EnumWindowsProcDelegate, ByVal lParam As Integer) As Integer
        Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As IntPtr, ByVal lpString As String, ByVal cch As Integer) As Integer
        Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As IntPtr) As Integer
        Delegate Function EnumWindowsProcDelegate(ByVal hwnd As IntPtr, ByVal lparam As Integer) As Boolean
        Public Declare Function DestroyWindow Lib "user32" (ByVal HWND As Integer) As Long
        Public numHWD As Long
    
    
     Public Sub ChiudiTaskManager()
            Dim prova33 As Boolean
            numHWD = 0
            prova33 = EnumWindows(AddressOf EnumWindowsProc, &H0)
            If numHWD > 0 Then Call DestroyWindow(numHWD)
        End Sub
    
        Public Function EnumWindowsProc(ByVal HWND As Integer, ByVal lParam As Integer) As Boolean
            Dim sSaVe As String, RET As Integer
            RET = GetWindowTextLength(HWND)
            sSaVe = Space(RET)
            GetWindowText(HWND, sSaVe, RET + 1)
            If sSaVe.Trim <> "" Then
                If InStr(1, LCase(sSaVe), "task manager", vbTextCompare) > 0 Then numHWD = HWND
            End If
            EnumWindowsProc = True   'continua enumerazione
        End Function

  6. #6
    Utente di HTML.it L'avatar di Vinsent
    Registrato dal
    May 2011
    Messaggi
    314
    Originariamente inviato da mvent
    Ecco, ho trovato anche questa funzione, da mettere sul form:

    codice:
     Protected Overrides Function ProcessCmdKey _
           (ByRef msg As System.Windows.Forms.Message, _
            ByVal keyData As System.Windows.Forms.Keys) As Boolean
    
            '********************************************************
            'DA COMMENTARE IN RELEASE
            'questo:
            MsgBox(keyData & " " & keyData.ToString)
            'in fase di debug scrive nell'output le informazioni
            'sul tasto premuto, serve per identificare il valore 
            '"keydata" da inserire nella lista.
            '********************************************************
    
            If keyData = 262162 Then msg = Nothing 'tasto ALT
            If keyData = 262162 Then keyData = 0 'tasto ALT
          
      If keyData = 115 Then keyData = 0 'tasto F4
      If keyData = 115 Then msg = Nothing 'tasto F4
    
            Return MyBase.ProcessCmdKey(msg, keyData)
    
        End Function
    riesce ad intercettare tutti i tasti ma ho provato a annullare le due variabili nel caso di pressione di ALT e di F4 e non funziona...

    Intercetti i singoli tasti e non la combinazione, il valore è 262259. Inoltre devi lavorare su "msg" è non su "keyData" perchè il tasto è "contenuto" in msg, quindi per Alt+F4 basta una riga:
    codice:
    If keyData = 262259 Then msg = Nothing
    In ogni caso, anche usando WndProc, puoi intervenire solo sul tuo programma mentre per tutto quello che è gestito direttamente da Windows devi usare per forza le sue API.
    Ciao

  7. #7
    Utente di HTML.it L'avatar di oregon
    Registrato dal
    Jul 2005
    residenza
    Roma
    Messaggi
    36,480
    Ma perché tutto ciò ? Impedire il task manager ? Sembra un malware ...
    No MP tecnici (non rispondo nemmeno!), usa il forum.

  8. #8
    Utente di HTML.it L'avatar di mvent
    Registrato dal
    Jun 2002
    Messaggi
    230
    Originariamente inviato da oregon
    Ma perché tutto ciò ? Impedire il task manager ? Sembra un malware ...
    ho fatto uno screensaver protetto da password e quindi il programma non serve a niente se l'utente può chiuderlo facendo le classiche combinazioni di tasti.

    So che esiste Tasto Windows + L per rimandare alla schermata di logon ma in alcuni casi i pc non hanno impostata (e gli utenti non vogliono impostare) una password di logon.

    E' esattamente il mio caso: io ho una password sul disco fisso che viene richiesta all'avvio del pc, come prima cosa, ma non ho impostato e non voglio impostare una password sul logon di windows. Tuttavia, ho bisogno che quando mi allontano dal pc per qualche minuto, lasciandolo acceso, nessuno ci vada a spiticchiare.

  9. #9
    Utente di HTML.it L'avatar di mvent
    Registrato dal
    Jun 2002
    Messaggi
    230
    Originariamente inviato da Vinsent
    Intercetti i singoli tasti e non la combinazione, il valore è 262259. Inoltre devi lavorare su "msg" è non su "keyData" perchè il tasto è "contenuto" in msg, quindi per Alt+F4 basta una riga:
    codice:
    If keyData = 262259 Then msg = Nothing
    In ogni caso, anche usando WndProc, puoi intervenire solo sul tuo programma mentre per tutto quello che è gestito direttamente da Windows devi usare per forza le sue API.
    Ciao
    Grazie Vinsent!

    Accidenti, non ci avevo proprio neanche pensato!

    In effetti per ovviare a questo problema ho alcune Api per bloccare il mouse. In questo modo, anche se, giustamente, come hai scritto tu, quel controllo tasti vale solo sul form, nel mio caso andrebbe bene: il form viene caricato massimizzato a tutto schermo; il mouse è bloccato. Pertanto l'unico modo che ha l'utente per uscire è quello di usare qualche combinazione di tasti ma in questo caso le combinazioni le intercetto sul mio form e le blocco. In questo modo può uscire solo digitando una password.

  10. #10
    Originariamente inviato da mvent
    ....Tuttavia, ho bisogno che quando mi allontano dal pc per qualche minuto, lasciandolo acceso, nessuno ci vada a spiticchiare.
    ma scusa, windows prevede di impostare lo screensaver con la richiesta di password alla sblocco...non ti va bene?? Sinceramente non capisco proprio dove vuoi arrivare... come si dice..a pensar male non si sbaglia mai
    Jupynet

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.