consoletimerwake.pas

来自「delphi源代码分析源码」· PAS 代码 · 共 55 行

PAS
55
字号
unit ConsoleTimerWake;

interface
uses
  Windows, Messages, Classes;

var
  // 用于替代System.MainThreadID;
  MainThreadID : Cardinal;

implementation

procedure WakeConsole(Sender: TObject);
begin
  PostThreadMessage(MainThreadId, WM_TIMER, 0, 0);
end;

var
  WakeMainThread : TMethod = (Code:@WakeConsole; Data:Nil);
  WatchThreadHandle : Cardinal; // 处理消息循环的线程句柄

procedure TimerCallBack(hWnd: HWND; Msg, idEvent: UINT; dwTime: DWORD); stdcall;
begin
  Classes.CheckSynchronize;
end;

function WatchThreadFunc(Parameter: Pointer): Integer; stdcall;
var
  TimerHandle : THandle;
  Msg : TMsg;
begin
  Classes.WakeMainThread := TNotifyEvent(WakeMainThread);
  TimerHandle := SetTimer(0, 0, 100, @TimerCallBack);
  if TimerHandle = 0 then
    writeln('could not create timer')
  else
  begin
    repeat
      GetMessage(Msg, 0, 0, 0);
      DispatchMessage(Msg);
    until (Msg.Message = WM_QUIT);
    KillTimer(0, TimerHandle);
  end;
end;

initialization
  MainThreadID := System.MainThreadID;
  WatchThreadHandle := CreateThread(nil, 0, @WatchThreadFunc, nil, 0, System.MainThreadID);

finalization
  CloseHandle(WatchThreadHandle);
  System.MainThreadID := MainThreadID;

end.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?