有不少人討論過顯示系統鍵(CapsLock、NumLock、Insert、ScrollLock等)狀態的問題,用得最多的方法是添加一個Timer,在事件中刷新系統鍵狀態顯示;另一個方法是做一個系統HOOK,在HOOK中刷新顯示。這兩種方式都會嚴重占用系統資源,第一種方法還存在延遲的問題。現在介紹第三種方法:
鍵盤按鈕被按下時系統會發送WM_KEYDOWN、WM_CHAR、WM_KEYUP消息給當前的激活應用程序,消息的wParam是鍵盤掃描碼,這樣我們就可以知道按鍵是否被按下或釋放,在這里面刷新按鍵狀態顯示是最佳的時候。不過這里還有一個問題,應用程序在非激活狀態時是收不到以上消息的,因此需要在程序被激活時檢測并刷新狀態顯示。
下面給出實現代碼:
unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls;
type
  TForm1 = class(TForm)
    StatusBar1: TStatusBar;
    PRocedure FormCreate(Sender: TObject);
  private
    procedure AppActivate(Sender: TObject);
    procedure AppOnMsg(var Msg: tagMSG; var Handled: Boolean);
    procedure ShowKeyState; //顯示系統按鍵狀態
end;
var
  Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
    //顯示系統鍵狀態,指定事件代理
    ShowKeyState;
    application.OnMessage := AppOnMsg;
    Application.OnActivate := AppActivate;
end;
procedure TForm1.AppActivate(Sender: TObject);
begin
    ShowKeyState;   //應用程序被激活時刷新系統鍵狀態
end;
procedure TForm1.ShowKeyState;
begin
    if (GetKeyState(145) and 1)<>0 then
        StatusBar1.Panels.Items[6].Text := 'SCOR'
    else
        StatusBar1.Panels.Items[6].Text := '';
    if (GetKeyState(144) and 1)<>0 then
        StatusBar1.Panels.Items[5].Text := 'NUM'
    else
        StatusBar1.Panels.Items[5].Text := '';
    if (GetKeyState(45) and 1)<>0 then
        StatusBar1.Panels.Items[4].Text := '插入'
    else
        StatusBar1.Panels.Items[4].Text := '覆蓋';
    if (GetKeyState(20) and 1)<>0 then
        StatusBar1.Panels.Items[3].Text := '大寫'
    else
        StatusBar1.Panels.Items[3].Text := '小寫';
end;
procedure TForm1.AppOnMsg(var Msg: tagMSG; var Handled: Boolean);
begin
    if Msg.message = 256 then begin //WM_KEYDOWN
        case Msg.wParam of  //根據按鍵切換顯示
            145:  //Scorll
                if (GetKeyState(145) and 1)<>0 then
                    StatusBar1.Panels.Items[6].Text := 'SCOR'
                else
                    StatusBar1.Panels.Items[6].Text := '';
            144:   //Num
                if (GetKeyState(144) and 1)<>0 then
                    StatusBar1.Panels.Items[5].Text := 'NUM'
                else
                    StatusBar1.Panels.Items[5].Text := '';
            45:   //Ins
                if (GetKeyState(45) and 1)<>0 then
                    StatusBar1.Panels.Items[4].Text := '插入'
                else
                    StatusBar1.Panels.Items[4].Text := '覆蓋';
            20:   //Caps
                if (GetKeyState(20) and 1)<>0 then
                    StatusBar1.Panels.Items[3].Text := '大寫'
                else
                    StatusBar1.Panels.Items[3].Text := '小寫';
        end;
    end;
    Handled := false;   //讓系統繼續處理消息
end;
end.
新聞熱點
疑難解答