Friday, June 17, 2005

Setting Focus with MessageDlg

One of the things I've had to do manually many times is to have dialog boxes pop up, but logically "OK" should not be the focussed button. (Like "Do you want to format this disk?")


In Delphi, you'd usually call MessageDlg for a dialog that had a Yes/No/Cancel or an Ok/Cancel input only - but that doesn't give you a way to change the focus or default button. So here's how you would do it - call MessageDlgFocus instead:


var
ButtonNames: array[TMsgDlgBtn] of string = (
'Yes', 'No', 'OK', 'Cancel', 'Abort', 'Retry', 'Ignore',
'All', 'NoToAll', 'YesToAll', 'Help');

function MessageDlgWithFocus(const Msg: string;
DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons;
FocusBtn: TMsgDlgBtn;
HelpCtx: Longint): Integer;
var Btn: TComponent;
begin
with CreateMessageDialog(Msg, DlgType, Buttons) do
try
HelpContext := HelpCtx;
Position := poScreenCenter;

Btn := FindComponent( ButtonNames[FocusBtn] );
if (Btn <> nil) and (Btn is TWinControl) then
ActiveControl := Btn as TWinControl;

Result := ShowModal;
finally
Free;
end;
end;


Call it with:

MessageDlgWithFocus('test', mtCOnfirmation,
[mbOk, mbCancel], mbCancel, 0);


This code will bring up a dialog with OK and Cancel buttons, and the Cancel button is focussed.

2 Comments:

Anonymous Anonymous said...

I don't have a dev. box with me, but doesn't Application.MessageBox() give you the facility to set focus to any button you choose? You could (of course) wrap the call to Application.MessageBox() to use the exact same parameters as MessagdDlg().

3:25 AM  
Blogger giltonic said...

Diego, The MessageBox() is great but not exactly like MessageDlg().
Because "MessageBox" is not a modal box. So, you can complety ignore it.

So thank you very much Deepak Shenoy for your code.

Bye.

3:02 AM  

Post a Comment

<< Home