Title: Putting a custom icon on a MessageBox
Question: Is it possible to specify an icon for the MessageBox function other than the default warning, info, question, error, winlogo and app?
Answer:
The following shows how you can use the MessgeBoxIndirect API function. It takes as its parameter a structure which contais the description of the messagebox to build. I encapsulated this API function in a procedure called MyAboutBox, which will show a MessageBox with the application main icon:
{--snip--}
procedure MyAboutBox(Text: String);
var
MsgPars: TMsgBoxParams;
begin
with MsgPars do
begin
cbSize := SizeOf(MsgPars);
hwndOwner := Sysinit.HInstance;
hInstance := Sysinit.hInstance; //where to find resources
lpszText := PChar(Text); //if using Delphi 1, must use StrPCopy.
lpszCaption := 'About';
dwStyle := MB_OK or MB_USERICON;
lpszIcon := 'MAINICON'; //app's main icon, icluded in the *.exe
dwContextHelpId := 0; //help context
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
end; //with
MessageBoxIndirect(MsgPars);
end;
{--snip--}
Then, you could use it in a event handler, like this:
{--snip--}
procedure TForm1.Button1Click(Sender: TObject);
begin
MyAboutBox('Example of changing the default MessageBox icons'#13 +
'by Odilon Nelson - odilon.nelson@usa.net');
end;
{--snip--}
Note that, in the MyAboutBox proc, I used the following:
{--snip--}
hwndOwner := Sysinit.HInstance;
hInstance := Sysinit.hInstance;
{--snip--}
Well, I did this to avoid confusion between the two hinstance variables, since I'm using a *with* statement. One is the hinstance member of the TMsgBoxParams record, the other is the handle of the app, defined (and initialized) in the Sysinit unit
(remember that ObjectPascal is NOT case sensitive: hInstance and HInstance mean the same).
The lpszIcon member of the TMsgBoxParams record represents the resource name of the compiled icon. Hence, you could reference any resource icon in your app. I used the main app icon just as a convenience.
The advantage of this approach is quite obvious: you have an about box, with no need to include an extra form in your project.