Windows VistaWindows 2003Visual Studio 2005Windows 2000Windows XP.NET 2.0初学者开发Visual StudioWindows.NETC#
C# MDI 入门示例





1.00/5 (1投票)
一个简单的 MDI(多文档界面)示例。
引言
这是我的第一篇文章,请原谅其粗糙之处。该程序的目的是让读者从 (MDI) 多文档界面入手,当他们习惯于编写单文档程序时。基本上,该程序只是演示了如何跟踪用户正在使用的窗体,以便“主菜单”可以正确运行,这也可以扩展为表示主窗体如何与子文档窗体通信。
背景
快速概览是,我启动了 VS2005,使用一个空项目,创建了一个 MDI 窗体,并创建了一个变量来跟踪用户正在使用的文档。然后我使用了 MDI 子窗体的 Active
事件函数来更新我的焦点跟踪变量。如果上一句话让你感到困惑,请不要担心。我已经发布了代码,它大部分都是直接且简单的。
Using the Code
我希望写一些深刻的解释,但下面的代码几乎就是它的全部。focusChild
是一个私有的全局窗体变量,它会在焦点更改子窗体时被赋值。
private void MDIParent1_MdiChildActivate(object sender, EventArgs e)
{
//MessageBox.Show("something was activated");
focusChild = null;
foreach (Form childForm in this.MdiChildren)
{
if (childForm.ContainsFocus)
{
focusChild = (txtForm)childForm;
if (!childForm.Text.Contains("Focused"))
childForm.Text += " Focused";
}
else
if (childForm.Text.Contains("Focused"))
childForm.Text = childForm.Text.Remove(
childForm.Text.IndexOf("Focused")-1);
}
}
唯一值得一提的另一件事是当用户从主菜单单击“打开/保存”按钮时会发生什么。下面是 Save
事件,它使用跟踪变量并从我们的自定义窗体中提取数据并将其保存到文件中。
private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
{
string FileName = saveFileDialog.FileName;
// TODO: Add code here to save the current contents of the form to a file.
if (focusChild != null)
{
using (StreamWriter sw = new StreamWriter(FileName))
{
foreach (string line in focusChild.richTextBox1.Lines)
sw.WriteLine(line);
sw.Flush();
sw.Close();
}
}
}
}
关注点
值得注意的是,我使用了上面的 childForm.ContainsFocus
属性是有原因的。如果窗体或其任何组件具有焦点,ContainsFocus
将返回 true
。form.focus
仅当窗体本身具有焦点时才返回 true
。
历史
只是一个快速且简单的示例,至今没有更改。