Get/Change key states for NumLock, CapsLock and ScrollLock  

Send By: Q3 Team
Web : http://www.q3.nu
Email: dlib@q3.nu
Date: 06/02/04

Tip accessed 829 times

 


Get the status of one of this keys with GetKeyState:


 procedure TForm1.Button1Click(Sender: TObject);
 begin
   If GetKeyState(VK_NUMLOCK)=1
     then ShowMessage('Conectada')
     else ShowMessage('Desconectada');
 end;



VK_ codes for this key types:
  • VK_NUMLOCK = NumLock state
  • VK_CAPITAL = Capitals
  • VK_SCROLL = ScrollLock state


    We can also obtain all keyboard status, and later, look for the state of the keys, with GetKeyboardState:


     procedure TForm1.Button2Click(Sender: TObject);
     var
        Teclado: TKeyboardState;
     begin
       GetKeyboardState(Teclado);
       If Teclado[VK_NUMLOCK]=1
         then ShowMessage('Conectada')
         else ShowMessage('Desconectada');
     end;
    




    Finally, we can to set this states with SetKeyboardState:


     procedure TForm1.Button3Click(Sender: TObject);
     var
        Teclado: TKeyboardState;
     begin
       {Leemos estado actual del teclado}
       {Read current keyboard status}
       GetKeyboardState(Teclado);
       {Activamos mayúsculas/Set capitals}
       Teclado [VK_CAPITAL]:=1;
       {Desactivamos NumLock/Deactivate NumLock}
       Teclado [VK_NUMLOCK]:=0;
       SetKeyboardState(Teclado);
     end;
    


    NOTE: Something has changed since Delphi3 and Windows 98, and this code doesn't work...


    Other method for all kind of Windows:


     procedure TForm1.Button3Click(Sender: TObject);
    
       procedure FijaTecla(VKTecla: Integer; Activar: Boolean);
       begin
         if (GetKeyState(VKTecla)=1) <> Activar then
         begin
           {Simulamos una pulsación de la tecla}
           {Simulate a key press}
           keybd_event( VKTecla,0,
                        KEYEVENTF_EXTENDEDKEY, 0);
    
           {Simulamos que soltamos la tecla}
           {Simulate key-release}
           keybd_event( VKTecla,0,
                        KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
         end;
       end;
    
     begin
       {-------- Ejemplos de llamada}
       {-------- Call examples}
    
       {Activar Bloq Num}
       {Activate Num Lock}
       FijaTecla(VK_NUMLOCK, True);
    
       {Desactivar Mayúsculas}
       {Deactivate Capital Lock}
       FijaTecla(VK_CAPITAL, False);
     end;
    


    Consists in simulate the key press, for change its state.


    Updated at 06/02/2004 Second Method