Re: How to place focus back after error message window closed?

Tech-Archive recommends: Fix windows errors by optimizing your registry



Well, the reason the code doesn't put the focus back where you want it is that, well, the
code DOESN'T put the focus back where you want it! Where, exactly, did you do anything
that would result in the focus going anywhere?

First observation: if the field values are not correct, why is the OK button enabled? You
should not enable it unless there is a valid set of fields.

I would handle this as I describe in my essay on dialog control management:

void CMochikoshiDlg::updateControls()
{
c_OK.EnableWindow(
!m_edt_mochi_date_year.IsEmpty() &&
!m_edt_mhoci_date_month.IsEmpty() &&
!m_edt_mochi_date_day.IsEmpty());
}

then you would add EN_CHANGE notifications

void C...Dlg::OnChangeMochiDateYear()
{
updateControls();
}
....etc.

If the fields are not OK, the OK button should be disabled! It makes no sense to click it
if the fields are not correct.

In the updateControls function, you can do things like show an error message (in a
CStatic) that says that the fields are incomplete. I've even used a tooltip, hovering
over the OK button that is disabled shows a tooltip saying there is a missing year field;
if the year field is filled in and the month field is empty, it says there is no month
field, etc. If all fields are valid, the tooltip says "Accept changes" or something
appropriate.

If you want to set the focus back to a control, there is a SetFocus method you must call
to do this!

For example:

CString s;
c_Year.GetWindowText(s);
s.Trim();
if(s.IsEmpty())
{
c_Year.SetFocus();
return;
}
c_Month.GetWindowText(s);
s.Trim();
if(s.IsEmpty())
{
c_Month.SetFocus();
return;
}

etc.

The use of string variables suggests you are using UpdateData to store the values. I
consider this a fundamental design error, and do my best to avoid ever seeing an
UpdateData anywhere in code (I have a reasonable confidence that if UpdateData appears in
a dialog, the code is wrong, and I've been right often enough that if I ever see it, I
remove it and replace it with appropriate requests to obtain values from the controls.
joe

On Tue, 13 May 2008 01:00:01 -0700, Landon <Landon@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:

I have a form with 3 CEdit which are Year, Month and Day fields.

If one of them is empty and user click OK or press Enter, an error message
will displayed and the focus will back on where it was.

I have tried this code but it won't focused back on where it was, it just
back to the form but nothing is focused.

void CMochikoshiDlg::OnOK()
{
// TODO: ?????????????????????????
if ( m_edt_mochi_date_year.IsEmpty() || m_edt_mochi_date_month.IsEmpty() ||
m_edt_mochi_date_day.IsEmpty() ) {
MessageBox( "Error" );
return;
}
CDialog::OnOK();
}

How to do that?

Thank you very much.
Joseph M. Newcomer [MVP]
email: newcomer@xxxxxxxxxxxx
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
.


Quantcast