Non Visual Components (HBasicComponents.pas)

These VCL components provide file searching, background work, timers, keyboard and clipboard events, and a Windows notification icon.
Event handlers are methods of an object. Unless a section says otherwise, create the component with an owner or free it when finished.

ThComponent and message adapters

ThComponent
extends TComponent with a Windows message handle. It is the base class of ThTimer, TClipboardChanged, and TTaskbarIcon.
Its virtual Adapter_Message lets descendants handle messages. Set Handled_By_Adapter to True when the message has been handled.
Constructor ThComponent.Create(AOwner: TComponent);
Destructor ThComponent.Destroy;
Property ThComponent.Handle: HWND;
Property ThComponent.Usage_Notes: String;
Procedure ThComponent.Adapter_Message(VAR _Message: TMessage;
  VAR Handled_By_Adapter: Boolean);
Handle is read only and is available on Windows. The constructor allocates it through Sync_Proc; the destructor releases it the same way.
Usage_Notes stores developer notes and defaults to an empty string.
ThDM_Message_Handler forwards messages to the callback supplied to its constructor. The callback receives the message and can mark it as handled.
ThMessage_Adapter = Procedure(VAR _Message: TMessage;
  VAR Handled_By_Adapter: Boolean) OF Object;
Constructor ThDM_Message_Handler.Create(AOwner: TComponent;
  CallEvent: ThMessage_Adapter);

ThFileSearch

Searches the file system and reports matches through OnFoundFile. Assign that event before starting a search. If SearchPath is empty, the component sets it to the application path. Both search methods return False if the path does not exist, the event is missing, or the callback sets Stop to True. A True result means the scan was not stopped; it does not mean a match was found.

Execute

Searches entries matching SearchMask in SearchPath. With AllFolders=True, it also visits subfolders. Matching entries may be files or directories; inspect the callback's Directory argument.
Function ThFileSearch.Execute: Boolean;

Scan_For_Directories

Reports directories only. Level 1 means immediate child directories; level 2 includes their children. A value of 0 is treated as 1. This method ignores SearchMask and AllFolders.
Function ThFileSearch.Scan_For_Directories(How_Many_Levels: Word): Boolean;

Settings and runtime tags

Property ThFileSearch.SearchMask: String;
Property ThFileSearch.SearchPath: String;
Property ThFileSearch.AllFolders: Boolean;
Property ThFileSearch.Usage_Notes: String;
Property ThFileSearch.OnFoundFile: ThFileSearchEventType;
ThFileSearch.rt_STag: Array[1..3] OF String;
ThFileSearch.rt_DTag: Array[1..3] OF Double;
ThFileSearch.rt_ITag: Array[1..3] OF Integer;
ThFileSearch.rt_BTag: Array[1..3] OF Boolean;
The defaults are SearchMask='*.*', an empty path, and AllFolders=True. The tag arrays are public storage for application data; the constructor clears them.

ThFileSearchEventType

ThFileSearchEventType = Procedure(Path, Name: String; Size: Int64;
  LastWriteTime_UTC: TDateTime; Directory: Boolean; Attr: String;
  VAR Stop: Boolean) OF Object;
Path is the containing directory and Name is the entry name. Size is the reported size in bytes; the directory only scan passes 0. LastWriteTime_UTC is the last write time in UTC. Attr contains any of R (read only), A (archive), H (hidden), and S (system). The directory only scan passes an empty attribute string. Set Stop=True to stop scanning.

Example

The event handler signature must match ThFileSearchEventType. This example prints file names and skips directory entries.
procedure TMyForm.FoundFile(Path, Name: String; Size: Int64;
  LastWriteTime_UTC: TDateTime; Directory: Boolean; Attr: String;
  var Stop: Boolean);
begin
  if not Directory then
    Memo1.Lines.Add(Path + Name);
end;

procedure TMyForm.FindFiles;
var
  Search: ThFileSearch;
begin
  Search := ThFileSearch.Create(Self);
  try
    Search.SearchPath := 'C:\Logs';
    Search.SearchMask := '*.log';
    Search.OnFoundFile := FoundFile;
    Search.Execute;
  finally
    Search.Free;
  end;
end;

ThThread

Runs OnExecute on a Windows worker thread. The optional completion callbacks run after each execution: After_Exec_Under_Thread on the worker, then After_Exec_On_App_Thread through TThread.Synchronize. Do not access VCL controls from the worker callback.
Keep_Thread_On_Hold defaults to True. In that mode the worker stays allocated and waits to be awakened for later work. Set it to False before starting work to use a new thread for each execution.

Execute_Thread and Thread_Is_Running

Procedure ThThread.Execute_Thread;
Function ThThread.Thread_Is_Running: Boolean;
Execute_Thread returns without starting another execution if the worker is already running. Thread_Is_Running reports active execution or termination; a worker waiting on hold is not reported as running.

Wait_For_Thread

Waits for active work for up to Seconds seconds, capped at 1200. It returns immediately if called from its own worker, if the handle does not exist, or if Seconds is below 0.05. It processes application messages when called on the main thread. Waiting on the main thread may therefore run other UI event handlers.
Procedure ThThread.Wait_For_Thread(Seconds: Double);

Terminate_NOW_With_Memory_Leak

Signals termination and then forcibly terminates the Windows thread. This can interrupt work without cleanup and leak resources. Use only when a normal shutdown cannot finish the task.
Procedure ThThread.Terminate_NOW_With_Memory_Leak;

Other methods and properties

Procedure ThThread.Reset_RT_Tags;
Function ThThread.This_Line_Running_Under_Myself: Boolean;
Property ThThread.Command_For_Thread: Word;
Property ThThread.Keep_Thread_On_Hold: Boolean;
Property ThThread.Usage_Notes: String;
Property ThThread.OnExecute: TNotifyEvent;
Property ThThread.After_Exec_Under_Thread: TThreadMethod;
Property ThThread.After_Exec_On_App_Thread: TThreadMethod;
ThThread.rt_STag: Array[1..3] OF String;
ThThread.rt_DTag: Array[1..3] OF Double;
ThThread.rt_ITag: Array[1..3] OF Integer;
ThThread.rt_BTag: Array[1..3] OF Boolean;
Reset_RT_Tags clears the four public tag arrays. This_Line_Running_Under_Myself checks whether the caller is this component's worker thread. Command_For_Thread defaults to 0; its setter rejects a change while the worker is running. Set a command before calling Execute_Thread. Usage_Notes is a free text field.

Example

Assign the callback before starting the worker. Keep the component alive while its code may run.
procedure TMyForm.WorkerExecute(Sender: TObject);
begin
  // Perform background work without accessing VCL controls.
  Sleep(100); // Replace with application background work.
end;

procedure TMyForm.StartWork;
begin
  Worker.OnExecute := WorkerExecute;
  Worker.Execute_Thread;
end;

ThTimer

Uses a Windows timer and runs one callback at a time. Set a positive Interval in seconds and assign OnQue or Que_On_Thread before calling Run. If both events are assigned, Que_On_Thread takes precedence. The next repeated interval starts after the callback completes.

Run and Stop

Procedure ThTimer.Run(Once: Boolean = False);
Procedure ThTimer.Stop(Term_Thread_If_Exist: Boolean = False);
Run(True) schedules one callback; Run(False) repeats. Calling Run while active restarts the timer. Stop prevents further timer messages. With Term_Thread_If_Exist=True, it forcibly terminates an active worker by calling Terminate_NOW_With_Memory_Leak. The default leaves an already running worker to finish.

Status and runtime tags

Function ThTimer.Thread_Is_Running: Boolean;
Function ThTimer.Kill_Thread_IF_Running: Boolean;
Property ThTimer.Timer_Is_ON: Boolean;
Property ThTimer.Busy_On_Que: Boolean;
Procedure ThTimer.Reset_RT_Tags;
ThTimer.rt_Task: Word;
ThTimer.rt_STag: Array[1..3] OF String;
ThTimer.rt_DTag: Array[1..3] OF Double;
ThTimer.rt_ITag: Array[1..3] OF Integer;
ThTimer.rt_BTag: Array[1..3] OF Boolean;
ThTimer.rt_Write_Debug_Log: Boolean;
Timer_Is_ON reports whether the Windows timer was started; Busy_On_Que reports callback execution. Thread_Is_Running refers only to the internal worker, which exists after a thread callback has been requested. Kill_Thread_IF_Running returns whether the worker was running and forcibly terminates it if so. Reset_RT_Tags clears the tag arrays and sets rt_Task to 0. rt_Write_Debug_Log controls debug logging for one interval calculation and defaults to False.

Interval and events

Property ThTimer.Interval: Double;
Property ThTimer.OnQue: TNotifyEvent;
Property ThTimer.Que_On_Thread: TNotifyEvent;
Interval defaults to 10 seconds. Negative assignments are ignored. Changing it does not reschedule an active timer; call Run again. OnQue executes on the application thread and may update VCL controls. Que_On_Thread executes on a worker and must not directly update VCL controls.

Example

This schedules a single callback on the application thread after five seconds.
procedure TMyForm.TimerQue(Sender: TObject);
begin
  StatusLabel.Caption := 'Finished';
end;

procedure TMyForm.StartDelay;
begin
  DelayTimer.OnQue := TimerQue;
  DelayTimer.Interval := 5;
  DelayTimer.Run(True);
end;

Interval calculation

These methods set Interval; call Run to start the timer. Calc_Interval_By_DateTime accepts a target from 2 seconds to 15 days after From_Now. It rounds down to whole seconds and adds one second. If the range test fails, it sets Interval to 3600 and returns False.
Function ThTimer.Calc_Interval_By_DateTime(
  CONST From_Now, Future_Trigger: TDateTime): Boolean;
Function ThTimer.Calc_Interval_For_Next_Hour(
  CONST From_Now: TDateTime; CONST HH, MM: Word): Boolean;
Function ThTimer.Calc_Interval_For_Next_Round_Hour(
  PlusMinutes: Byte = 0): Boolean;
Function ThTimer.Calc_Interval_For_Next_Ten_Minute(
  From_Now: TDateTime; Every5min: Boolean = False): Boolean;
Function ThTimer.Calc_Interval_For_Next_Round_Minute: Boolean;
Method Calculated target
Calc_Interval_For_Next_Hour The next occurrence of HH:MM after From_Now. HH must be 0..23 and MM 0..59.
Calc_Interval_For_Next_Round_Hour The next round hour plus PlusMinutes, based on Server.NOW_UTC when available or Hapi.NOW_UTC.
Calc_Interval_For_Next_Ten_Minute The next 10 minute boundary after From_Now, or the next 5 minute boundary when Every5min=True.
Calc_Interval_For_Next_Round_Minute The next whole minute, based on Server.NOW_UTC when available or Hapi.NOW_UTC.
The round hour and round minute methods use UTC. Use a matching UTC time basis when interpreting their result.

Example

if DelayTimer.Calc_Interval_For_Next_Ten_Minute(Now, True) then
  DelayTimer.Run(True); // Run once at the next five-minute boundary.

ThKeyboardSpy

Uses TApplicationEvents.OnMessage to observe keyboard messages processed by this VCL application. It is not a system wide keyboard hook. It handles WM_KEYDOWN and WM_CHAR; it does not report key releases.
Property ThKeyboardSpy.Enabled: Boolean;
Property ThKeyboardSpy.Usage_Notes: String;
Property ThKeyboardSpy.OnKeyDown: ThKeyEvent;
Property ThKeyboardSpy.OnKeyPress: TKeyPressEvent;
ThKeyEvent = Procedure(Key: Word; Shift: TShiftState;
  VAR Handled: Boolean) OF Object;
Enabled defaults to False. OnKeyDown receives a virtual key code and modifier state; set Handled=True to consume the message. OnKeyPress receives Sender and Key for character codes 1..254. Set Key=#0 to consume the character. Usage_Notes stores developer notes.

TClipboardChanged

Joins the Windows clipboard viewer chain at construction and leaves it at destruction. The event fires when Windows sends WM_DRAWCLIPBOARD; inspect the clipboard inside the handler if its contents matter. The component does not filter clipboard data.
Property TClipboardChanged.OnClipboardChanged: TNotifyEvent;

TTaskbarIcon

Manages one Windows notification area icon. Assign an icon before calling Add; an empty icon is not added. The component also restores its icon after Windows Explorer recreates the taskbar.
Procedure TTaskbarIcon.Add;
Procedure TTaskbarIcon.Remove;
Procedure TTaskbarIcon.Generate_Taskbar_Text_Icon(
  Text: String; BgColor, FontColor: TColor);
Procedure TTaskbarIcon.Balloon(Title, MsgBody: String);
Property TTaskbarIcon.Icon: TIcon;
Property TTaskbarIcon.IconHint: String;
Property TTaskbarIcon.OnClick: TTaskClickEvent;
TTaskClickEvent = Procedure(RightButton: Boolean; MousePos: TPoint) OF Object;
Add shows the icon; Remove hides it. Generate_Taskbar_Text_Icon draws text in a 16 by 16 icon, assigns it, and calls Add. An empty Text does nothing. Use short text that fits the icon.
Balloon requests a notification with a title and message only while the icon is visible. Windows controls whether and how it appears. IconHint is limited to 127 characters; changing it or Icon updates an icon already shown.
OnClick receives RightButton=True for a right button or context menu message, otherwise False for a left click. MousePos is the cursor position in screen coordinates. Click events occurring within half a second of the previous accepted event are ignored.

Example

procedure TMyForm.ShowTrayIcon;
begin
  TrayIcon.Icon.Assign(Application.Icon);
  TrayIcon.IconHint := 'Hyper ERP/CRM';
  TrayIcon.Add;
end;