I created a small application that allows minimizing to the system tray by clicking on a pop-up menu item associated with the form.
The application adds an icon by calling the Shell_NotifyIcon
function and hides itself. To restore, simply click on the icon in the tray, the form is displayed and the icon disappears.
This all works as expected when I run the application from the project folder, but when it is run from another location (any location), the icon creation fails, with the error code I get using GetLastError
being 0x80004005
.
Here is the execution code:
procedure TMyForm.BMHideClick(Sender: TObject);
begin
Hide;
PowerNotifyIcon.uFlags := NIF_MESSAGE or NIF_ICON or NIF_GUID or NIF_TIP; {PowerNotifyIcon is a TNotifyIconData structure}
StrPLCopy(PowerNotifyIcon.szTip, ICON_TIP, Length(ICON_TIP)); {ICON_TIP is a predefined string constant}
if not Shell_NotifyIcon(NIM_ADD, @PowerNotifyIcon) then
begin
MessageBox(Handle, PChar(Format('Failed to create system tray icon. error code: 0x%x', [GetLastError])),
PChar('Error'), MB_OK or MB_ICONERROR);
Show;
Exit;
end;
Shell_NotifyIcon(NIM_SETVERSION, @PowerNotifyIcon);
end;
To restore the form, I handle the WM_SYSTEM_TRAY_MESSAGE
messages received from the icon:
procedure TMyForm.TrayIconProc(var Msg: TMessage);
begin
case LOWORD(Msg.LParam) of
{...}
NIN_SELECT, NIN_KEYSELECT, WM_CONTEXTMENU, WM_LBUTTONUP, WM_RBUTTONUP: begin
Show;
Shell_NotifyIcon(NIM_DELETE, @PowerNotifyIcon);
end;
end;
end;