创建程序界面
为了测试上面我们创建的各个类,下面建立一个简单的程序界面。该界面中只有一个"绘图"菜单,其中有4个菜单选项,分别实现绘制直线段、圆、圆孤和文本。
首先创建一个新项目"NET_CAD",将窗体的背景色换成白色,如图4-2所示。然后在工具箱中单击"MainMenu"按钮,在窗体上进行拖曳,将在窗体的顶部显示菜单条,在"请在此处输入"字样处输入菜单或菜单项的名称,创建"绘图"菜单,其程序界面如图4-2所示。各菜单项的名称、标注和说明如表4-1所示。
\[\]
图4-2程序界面
表4-1
创建测试代码
前面已经创建了图元类、交互绘图类和基本的程序界面,可以说万事俱备,只欠东风了,下面创建响应菜单聊事的测试代码, 它们定义类与前端界面之间的联系。
VC#.NET中没有全局变量,所以程序中把这一类变量作为参数进行传递,在Form1类中声明它们。
code.vc#.net
private ArrayList ges=new ArrayList();
private ArrayList geSels=new ArrayList();
private ICommand aCommand;
private CCreateLine creLine=new CCreateLine();
private CCreateRectangle creRect=new CCreateRectangle();
private CCreateCircle creCircle=new CCreateCircle();
private CCreateArc creArc=new CCreateArc();
private CCreateText creText=new CCreateText();
private System.Windows.Forms.MenuItem mnuRect;
private System.Windows.Forms.MenuItem mnuCircle;
private Module m=new Module();
然后在Form1类中添加下面的代码。其中,OnPaint方法、OnMouseDown方法和OnMouseMove方法分别重写基类中对应的方法。其他各方法为单击"绘图"菜单中各菜单项时的响应代码。
code.vc#.net
private void mnuLine_Click(object sender, System.EventArgs e)
{
aCommand=creLine;
}
private void mnuRect_Click(object sender, System.EventArgs e)
{
aCommand=creRect;
}
private void mnuCircle_Click(object sender, System.EventArgs e)
{
aCommand=creCircle;
}
private void mnuArc_Click(object sender, System.EventArgs e)
{
aCommand=creArc;
}
private void mnuText_Click(object sender, System.EventArgs e)
{
aCommand=creText;
}
protected override void OnMouseDown(MouseEventArgs e)
{
Graphics g=this.CreateGraphics();
PointF aPos=m.PagetoWorld(new PointF(e.X, e.Y));
if(e.Button==MouseButtons.Left)
{
aCommand.LButtonDown(g,aPos,ges,geSels);
}
else if(e.Button==MouseButtons.Right)
{
aCommand.RButtonDown(g,aPos);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
Graphics g=this.CreateGraphics();
PointF aPos=m.PagetoWorld(new PointF(e.X, e.Y));
aCommand.MouseMove(g,aPos);
}
现在运行程序。图4-3是一个交互绘图效果的示例。
\[\]
图4-3交互绘图示例