Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
C# / VB.NET - [C#] Disabilitare Tastiera
Forum - C# / VB.NET - [C#] Disabilitare Tastiera

Avatar
Best (Normal User)
Rookie


Messaggi: 24
Iscritto: 12/09/2010

Segnala al moderatore
Postato alle 22:23
Sabato, 25/06/2011
Salve a tutti,
come da titolo, avrei la necessità di disabilitare qualunque input da tastiera (compresi,quindi, i tasti Win, Ctrl e così via). Ho utilizzato la funzione BlockInput, ma quest'ultima, disabilita anche il mouse. Sono presenti diversi sorgenti in rete a tal proposito, ma la maggior parte di questi sono lunghi e macchinosi. Su msdn ho letto alcune reference su Keyboard Input, ma non riesco a trarne il codice che devo utilizzare.

Grazie in anticipo.

EDIT

Ho sbagliato ad inserire il commento, comunque, grazie pierotofy per aver risposto alla mia domanda. Girando un pò per la rete ho trovato questo codice (questa classe). Personalmente ancora non l'ho testato, in quanto vorrei prima capire il codice che implemento e non fare "pappa pronta". Il codice è il seguente

Codice sorgente - presumibilmente C++

  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5.  
  6. public class KeyboardHook : IDisposable
  7. {
  8.  
  9.   public enum Parameters
  10.   {
  11.     None ,
  12.     AllowAltTab ,
  13.     AllowWindowsKey ,
  14.     AllowAltTabAndWindows ,
  15.     PassAllKeysToNextApp
  16.   }
  17.  
  18.   //Internal parameters
  19.   private bool PassAllKeysToNextApp = false;
  20.   private bool AllowAltTab = false;
  21.   private bool AllowWindowsKey = false;
  22.  
  23.   //Keyboard API constants
  24.   private const int WH_KEYBOARD_LL = 13;
  25.   private const int WM_KEYUP = 0x0101;
  26.   private const int WM_SYSKEYUP = 0x0105;
  27.  
  28.   //Modifier key constants
  29.   private const int VK_SHIFT = 0x10;
  30.   private const int VK_CONTROL = 0x11;
  31.   private const int VK_MENU = 0x12;
  32.   private const int VK_CAPITAL = 0x14;
  33.  
  34.   //Variables used in the call to SetWindowsHookEx
  35.   private HookHandlerDelegate proc;
  36.   private IntPtr hookID = IntPtr.Zero;
  37.   internal delegate IntPtr HookHandlerDelegate (
  38.     int nCode , IntPtr wParam , ref KBDLLHOOKSTRUCT lParam );
  39.  
  40.  
  41.   public event KeyboardHookEventHandler KeyIntercepted;
  42.  
  43.   // Structure returned by the hook whenever a key is pressed
  44.   internal struct KBDLLHOOKSTRUCT
  45.   {
  46.     public int vkCode;
  47.     int scanCode;
  48.     public int flags;
  49.     int time;
  50.     int dwExtraInfo;
  51.   }
  52.  
  53.   #region Constructors
  54.  
  55.   public KeyboardHook ( )
  56.   {
  57.     proc = new HookHandlerDelegate ( HookCallback );
  58.     using ( Process curProcess = Process.GetCurrentProcess ( ) )
  59.     using ( ProcessModule curModule = curProcess.MainModule )
  60.     {
  61.       hookID = NativeMethods.SetWindowsHookEx ( WH_KEYBOARD_LL , proc ,
  62.         NativeMethods.GetModuleHandle ( curModule.ModuleName ) , 0 );
  63.     }
  64.   }
  65.  
  66.  
  67.   public KeyboardHook ( string param )
  68.     : this ( )
  69.   {
  70.     if ( !String.IsNullOrEmpty ( param ) && Enum.IsDefined ( typeof ( Parameters ) , param ) )
  71.     {
  72.       SetParameters ( ( Parameters ) Enum.Parse ( typeof ( Parameters ) , param ) );
  73.     }
  74.   }
  75.  
  76.  
  77.   public KeyboardHook ( Parameters param )
  78.     : this ( )
  79.   {
  80.     SetParameters ( param );
  81.   }
  82.  
  83.   private void SetParameters ( Parameters param )
  84.   {
  85.     switch ( param )
  86.     {
  87.       case Parameters.None:
  88.       break;
  89.       case Parameters.AllowAltTab:
  90.       AllowAltTab = true;
  91.       break;
  92.       case Parameters.AllowWindowsKey:
  93.       AllowWindowsKey = true;
  94.       break;
  95.       case Parameters.AllowAltTabAndWindows:
  96.       AllowAltTab = true;
  97.       AllowWindowsKey = true;
  98.       break;
  99.       case Parameters.PassAllKeysToNextApp:
  100.       PassAllKeysToNextApp = true;
  101.       break;
  102.     }
  103.   }
  104.   #endregion
  105.  
  106.   #region Check Modifier keys
  107.  
  108.   private void CheckModifiers ( )
  109.   {
  110.     StringBuilder sb = new StringBuilder ( );
  111.  
  112.     if ( ( NativeMethods.GetKeyState ( VK_CAPITAL ) & 0x0001 ) != 0 )
  113.     {
  114.       //CAPSLOCK is ON
  115.       sb.AppendLine ( "Capslock is enabled." );
  116.     }
  117.  
  118.     if ( ( NativeMethods.GetKeyState ( VK_SHIFT ) & 0x8000 ) != 0 )
  119.     {
  120.       //SHIFT is pressed
  121.       sb.AppendLine ( "Shift is pressed." );
  122.     }
  123.     if ( ( NativeMethods.GetKeyState ( VK_CONTROL ) & 0x8000 ) != 0 )
  124.     {
  125.       //CONTROL is pressed
  126.       sb.AppendLine ( "Control is pressed." );
  127.     }
  128.     if ( ( NativeMethods.GetKeyState ( VK_MENU ) & 0x8000 ) != 0 )
  129.     {
  130.       //ALT is pressed
  131.       sb.AppendLine ( "Alt is pressed." );
  132.     }
  133.     Console.WriteLine ( sb.ToString ( ) );
  134.   }
  135.   #endregion Check Modifier keys
  136.  
  137.   #region Hook Callback Method
  138.  
  139.   private IntPtr HookCallback (
  140.     int nCode , IntPtr wParam , ref KBDLLHOOKSTRUCT lParam )
  141.   {
  142.     bool AllowKey = PassAllKeysToNextApp;
  143.  
  144.     //Filter wParam for KeyUp events only
  145.     if ( nCode >= 0 )
  146.     {
  147.       if ( wParam == ( IntPtr ) WM_KEYUP || wParam == ( IntPtr ) WM_SYSKEYUP )
  148.       {
  149.  
  150.  
  151.         if ( !( lParam.vkCode >= 160 && lParam.vkCode <= 164 ) )
  152.         {
  153.           CheckModifiers ( );
  154.         }
  155.  
  156.  
  157.         if ( AllowWindowsKey )
  158.         {
  159.           switch ( lParam.flags )
  160.           {
  161.             //Ctrl+Esc
  162.             case 0:
  163.             if ( lParam.vkCode == 27 )
  164.               AllowKey = true;
  165.             break;
  166.  
  167.             //Windows keys
  168.             case 1:
  169.             if ( ( lParam.vkCode == 91 ) || ( lParam.vkCode == 92 ) )
  170.               AllowKey = true;
  171.             break;
  172.           }
  173.         }
  174.         // Alt+Tab
  175.         if ( AllowAltTab )
  176.         {
  177.           if ( ( lParam.flags == 32 ) && ( lParam.vkCode == 9 ) )
  178.             AllowKey = true;
  179.         }
  180.  
  181.         OnKeyIntercepted ( new KeyboardHookEventArgs ( lParam.vkCode , AllowKey ) );
  182.       }
  183.  
  184.       //If this key is being suppressed, return a dummy value
  185.       if ( AllowKey == false )
  186.         return ( System.IntPtr ) 1;
  187.     }
  188.     //Pass key to next application
  189.     return NativeMethods.CallNextHookEx ( hookID , nCode , wParam , ref lParam );
  190.  
  191.   }
  192.   #endregion
  193.  
  194.   #region Event Handling
  195.  
  196.   public void OnKeyIntercepted ( KeyboardHookEventArgs e )
  197.   {
  198.     if ( KeyIntercepted != null )
  199.       KeyIntercepted ( e );
  200.   }
  201.  
  202.  
  203.   public delegate void KeyboardHookEventHandler ( KeyboardHookEventArgs e );
  204.  
  205.  
  206.   public class KeyboardHookEventArgs : System.EventArgs
  207.   {
  208.  
  209.     private string keyName;
  210.     private int keyCode;
  211.     private bool passThrough;
  212.  
  213.  
  214.     public string KeyName
  215.     {
  216.       get { return keyName; }
  217.     }
  218.  
  219.  
  220.     public int KeyCode
  221.     {
  222.       get { return keyCode; }
  223.     }
  224.  
  225.  
  226.     public bool PassThrough
  227.     {
  228.       get { return passThrough; }
  229.     }
  230.  
  231.     public KeyboardHookEventArgs ( int evtKeyCode , bool evtPassThrough )
  232.     {
  233.       keyName = ( evtKeyCode ).ToString ( );
  234.       keyCode = evtKeyCode;
  235.       passThrough = evtPassThrough;
  236.     }
  237.  
  238.   }
  239.  
  240.   #endregion
  241.  
  242.   #region IDisposable Members
  243.  
  244.   public void Dispose ( )
  245.   {
  246.     NativeMethods.UnhookWindowsHookEx ( hookID );
  247.   }
  248.   #endregion
  249.  
  250.   #region Native methods
  251.  
  252.   [ComVisibleAttribute ( false ) ,
  253.    System.Security.SuppressUnmanagedCodeSecurity ( )]
  254.   internal class NativeMethods
  255.   {
  256.     [DllImport ( "kernel32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
  257.     public static extern IntPtr GetModuleHandle ( string lpModuleName );
  258.  
  259.     [DllImport ( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
  260.     public static extern IntPtr SetWindowsHookEx ( int idHook ,
  261.       HookHandlerDelegate lpfn , IntPtr hMod , uint dwThreadId );
  262.  
  263.     [DllImport ( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
  264.     [return: MarshalAs ( UnmanagedType.Bool )]
  265.     public static extern bool UnhookWindowsHookEx ( IntPtr hhk );
  266.  
  267.     [DllImport ( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
  268.     public static extern IntPtr CallNextHookEx ( IntPtr hhk , int nCode ,
  269.       IntPtr wParam , ref KBDLLHOOKSTRUCT lParam );
  270.  
  271.     [DllImport ( "user32.dll" , CharSet = CharSet.Auto , ExactSpelling = true , CallingConvention = CallingConvention.Winapi )]
  272.     public static extern short GetKeyState ( int keyCode );
  273.  
  274.   }
  275.  
  276.  
  277.   #endregion
  278. }




Ps. Sono riuscito ad utilizzare il codice, ho creato un nuovo file cs contenente questo codice. Nell' applicazione, basta creare un oggetto della classe KeyboardHook e ovviamente associarlo ad un evento. Per "sbloccare" la tastiera, basta distruggere l'oggetto.


Ultima modifica effettuata da Best il 27/06/2011 alle 11:33
PM
Avatar
pierotofy (Admin)
Guru^2


Messaggi: 6225
Iscritto: 04/12/2003

Up
1
Down
V
Segnala al moderatore
Postato alle 23:05
Sabato, 25/06/2011
Non c'è un modo semplice; devi usare gli hook di sistema.

http://msdn.microsoft.com/en-us/library/ms644990%28v=vs.85 ...

Ciao pierotoy, - Best - 26/06/11 14:06


Il mio blog: https://piero.dev
PM