22.1.10 使用对话框(1)
我们将在Limits菜单的Upper和Lower菜单项的Click事件处理程序中使对话框可用。为了使之作为模态对话框显示,调用对话框对象的ShowDialog()函数。也可以选择将指向父窗体的句柄作为实参传递给ShowDialog()函数。下面是Click事件处理程序函数的实现:
- System::Void lowerMenuItem_Click(System::Object^ sender,
- System::EventArgs^ e)
- {
- if(lottoTab->Visible)
- {
- lottoLimitsDialog->SetLowerEnabled();
- ::DialogResult result = lottoLimitsDialog->ShowDialog(this);
-
- if(result == ::DialogResult::OK)
- {
- // Update user limits from dialog properties
- lottoUserMaximum = lottoLimitsDialog->UpperLimit;
- lottoUserMinimum = lottoLimitsDialog->LowerLimit;
- }
- }
- }
-
- System::Void upperMenuItem_Click(System::Object^ sender,
- System::EventArgs^ e)
- {
- if(lottoTab->Visible)
- {
- lottoLimitsDialog->SetUpperEnabled();
- ::DialogResult result = lottoLimitsDialog->ShowDialog(this);
-
- if(result == ::DialogResult::OK)
- {
- // Update user limits from dialog properties
- lottoUserMaximum = lottoLimitsDialog->UpperLimit;
- lottoUserMinimum = lottoLimitsDialog->LowerLimit;
- }
- }
- }
这两个函数都以相同的方式工作,它们都首先调用设置列表框状态的函数,然后调用对话框对象的ShowDialog()函数,使对话框以模态形式显示。如果我们希望使之成为非模态对话框,则应该调用对话框对象的Show()函数。
调用ShowDialog()函数之后,该函数直到对话框关闭之后才能返回。这意味着直到lottoOK按钮的Click事件处理程序把新的极限值存入对话框对象之后,更新极限值的代码才会执行。调用Show()函数使对话框作为非模态对话框显示时,该函数将立即返回。因此,如果需要访问对话框中可能已经被修改的数据,则应当采用另外的方法。为对话框窗体添加Closing事件的处理程序函数是一种可能性,另一种方法是在关闭对话框的按钮的事件处理程序中处理数据的传输问题。
ShowDialog()函数的返回值属于枚举类型DialogResult,被存储在局部变量result中。从ShowDialog()函数返回的值指出对话框中被单击的是哪一个按钮,如果该值是枚举常量::DialogResult::OK,则表明被单击的是OK按钮。因此,这两个处理程序函数中的代码都仅当OK按钮用来关闭对话框时,才更新lottoUserMaximum和LottoUserMinimum字段。
注意::运算符在类型说明::DialogReult和表达式::DialogResult::OK中的用法。为了区分在全局作用域的枚举名称与作为Form1类成员的同名属性,DialogResult前面的作用域解析运算符是必需的。
当然,可以直接访问lottoLimitsDialog对象的DialogResult属性,因此可以将那条if语句写成:
- if(lottoLimitsDialog->DialogResult == ::DialogResult::OK)
- {
- // Update user limits from dialog properties
- lottoUserMaximum = lottoLimitsDialog->UpperLimit;
- lottoUserMinimum = lottoLimitsDialog->LowerLimit;
- }
前一个版本更好,因为可以更明显地表明是在检查ShowDialog()函数返回的值。
此刻,OK按钮的Click事件处理程序还没有验证输入值的有效性,当前很有可能将上限和下限设置为两个使程序不能为彩票记录生成6个独特号码的数值。可以使用窗体的DialogResult属性来处理该问题。
1. 验证输入的有效性
如果在Lotto记录中有6个独特的数值,则用户选择的上限和下限之间的差值必须大于或等于5。为了检查该条件,可以修改对话框类中OK按钮的Click事件处理程序:
- System::Void lottoOK_Click(System::Object^ sender, System::EventArgs^ e)
- {
- int upper = 0;
- int lower = 0;
- // If there's a currently selected upper limit item, save it
- if(lottoUpperList->SelectedItem != nullptr)
- upper = safe_cast<Int32>(lottoUpperList->SelectedItem);
-
- // If there's a currently selected lower limit item, save it
- if(lottoLowerList->SelectedItem != nullptr)
- lower = safe_cast<Int32>(lottoLowerList->SelectedItem);
-
- if(upper - lower < 5)
- {
- MessageBox::Show(L"Upper limit:" + upper + L" Lower limit:"+ lower +
- L"\nUpper limit must be at least 5 greater that the lower
- limit." +
- L"\nTry Again.",
- L"Limits Invalid",
- MessageBoxButtons::OK,
- MessageBoxIcon::Error);
- DialogResult = ::DialogResult::None;
- }
- else
- {
- upperupperLimit = upper;
- lowerlowerLimit = lower;
- }
- }