Setting focussed button with Message Dlg

Posted by on in Blogs
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.


Comments

  • Guest
    Steve Trefethen Friday, 17 June 2005

    Hi Deepak!

    Great idea, can you log this in QC so we can improve VCL with this tip.

    Thanks!

    -Steve

  • Guest
    Deepak Shenoy Friday, 17 June 2005

    Hey Steve,



    Created, QC # 13767 .



    Cheers!

    Deepak

  • Guest
    Steve Heights Monday, 20 June 2005

    Excellent idea. One thing seems to be missing, though: the HelpCtx.



    Shouldn't that be

    HelpContext := HelpCtx;

    instead of

    HelpContext := 0;





    Steve

  • Guest
    Deepak Shenoy Monday, 20 June 2005

    Hey Steve,



    Thanks for that - have changed it now!



    Cheers,

    Deepak

  • Guest
    Bhushan Lalwani Tuesday, 22 August 2006

    Hey Deepak thx a lot. SMART



    regards,

    Bhushan

  • Please login first in order for you to submit comments
  • Page :
  • 1

Check out more tips and tricks in this development video: