C_程序源代码

来源:互联网 发布:资源三号卫星数据下载 编辑:程序博客网 时间:2024/05/17 23:00
 

C#程序设计
一、实验名称:C#实验
二、实验目的:通过上机实际操作将平时课堂所学具体实现,通过该实验来检查自己的学习成功,并且发现平时学习中没有注意到的问题并解决之,从而加深对该门课程的以及C#语言的了解。
三、实验步骤:
实验一:C#编程环境
实验目的:
1. 熟悉掌握C#开发环境的安装与配置
2. 熟悉开发环境,编写控制台和窗口两个版本的hello world范例程序
实验内容:
实验1-1:编写一个控制台程序,并且输出“hello world!”
相关主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace hello_world
{
    class SY1_2
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}
抓图结果:
 
实验1-2:编写一个Windows应用程序,并且输出“hello world!”
相关主要代码:
namespace hello_world2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Hello World", "Message from C#");
        }

    }
}
抓图结果:
 
实验二:C#编程基础
实验目的:
1.熟悉掌握C#的各种数据类型,常量、变量的表达形式;
2.熟悉掌握C#的运算符和表达式;
3.熟悉掌握C#的语言,会使用顺序、选择、循环等语句结构编写程序;
4.熟悉掌握C#的数组,学会数组的定义、初始化以及数组的应用。
实验内容:
实验2-1:有红、黄、黑、白四色球各一个,放置在一个编号为1、2、3、4的四个盒子中,每个盒子放置一只球,它们的顺序不知。
甲、乙、丙三人猜测放置顺序如下:
甲:黑球在1号盒子,黄球在2号盒子;
乙:黑球在2号盒子,白球在3号盒子;
丙:红球在2号盒子,白球在4号盒子。
结果证明甲、乙、丙三人各猜中了一半,给出四色球放置在盒中的情况。
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY2_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c, d;
            for(a=1;a<=4;a++)
                for(b=1;b<=4;b++)
                    for(c=1;c<=4;c++)
                        if(a!=b&& b!=c&&c!=a)
                        {
                            d=10-a-b-c;
                            if((c==1&&b==4)&&(a==2&&d==3)  )
                            {
                                Console .Write ("红球放置在{0}号,黄球放置在{1}号,",a,b);
                                Console .WriteLine ("黑球放置在{0}号,白球放置在{1}号",c,d);
                            }
                        }

            Console .Read ();
        }
    }
}
抓图结果:
 
实验2-2:采用筛选法求2-64之间的质数。
相关主要代码:
using System;
public class TestNumSort
{
    public static void Main()
    {
        int sieve, w;
        int i, j, p, k;
        bool flg = true;
        sieve = ~0x0;
        p = 3;
        for (i = 0; i < 32; i++)
        {
            w = 0x1 << i; w <<= p; j = p;
            while (j + i < 32)
            {
                sieve &= ~w;
                w <<= p; j += p;
            }
            k = i + 1;
            while (((sieve >> k) & 0x01) == 0)
            {
                k++; i++;
            }
            p = p + 2;
        }
        Console.WriteLine("2到64之间的素数有");
        Console.Write("{0,4}", 2);
        p = 3; w = 1;
        for (i = 0; i < 32; i++)
        {
            if ((sieve >> i & 0x01) != 0)
                Console.Write("{0,3}", p);
            p += 2;
        }
        Console.WriteLine();
        Console.Read();
    }
}
抓图结果:
 
实验2-3:根据给出的公式编程计算兀的值,直至所加项小于1E-10为止。
相关主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY2_3
{
    class Program
    {
        static void Main(string[] args)
        {
            double sum = 0.5, t, t1, t2, t3, p = 0.5 * 0.5;
            int odd = 3, even = 2, k;
            t = t1 = t2 = 1.0;
            t3= 1/2.0 ;
            while (t>1e-10)
            {
                even+=2;
                t2=1.0/odd ;
               t1=t1*(odd-2)/(even -2);
                odd+=2;
                t3=t3* (1/2.0)*(1/2.0) ;
                t = t1 * t3 * t2; 
                sum+=t;
            }
            Console .WriteLine ("\nPI={0,10:f8}",sum *6);
            Console .Read ();
        }
}
}

抓图结果:

 

实验2-4:编程进行卡布列克运算。所谓卡布列克运算,是指任意一个四位数,只要它们各个位上的数字不全相同,就有这样的规律:
1) 把组成这个四位数的四个数字由大到小排列,形成由这四个数字构成的最大数字
2) 把组成这个四位数的四个数字由小到大排列,形成由这四个数字构成的最小的四位数
3) 求出以上两数之差,得到一个新的四位数
重复以上过程,总能得到最后的结果是6174。
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY2_4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入一个4位整数");
            string s = Console.ReadLine();
            int num = Convert.ToInt32(s);
            int[] each = new int[4];
            int max, min, i, j, temp;
            while (num != 6174 && num != 0)
            {
                i = 0;
                while (num != 0)
                {
                   each [i++]=num%10; 
                   num=num/10;
                }

                for(i=0;i<3;i++)
                    for(j=0;j<3-i;j++)
                        if(each [j]>=each [j+1])
                        {
                            temp=each [j];
                            each [j]=each [j+1];
                            each [j+1]=temp;
                        }
                min= each [0]*1000+each [1]*100+each [2]*10+each [3]  ;
                max=  each [3]*1000+each [2]*100+each [1]*10+each [0]  ;
                num = max -min ;
                Console .WriteLine ("{0}-{1}={2}",max,min,num);

            }
            Console .Read();
        }
    }
}
抓图的结果:
 
实验2-5:数列A={1,1,3,7,17,41……}有以下性质:
a =a =1;
a =a +2a (i>1)
对于给定的n,数列的各个元素值由数列A的元素生成即以a / a 的分数形式表示,然后对其进行排序
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY2_5
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] A = new int[11];
            int [ ,]Fraction=new int[2,11];
            float []B=new float [10];
            int i,n,j,pos,temp;
            float ftemp;
            A[0]=A[1]=1;
            Console .Write ("\n请输入n(n<=10)值:");
            string s=Console .ReadLine ();
            n=Convert .ToInt32 (s);
            for(i=2;i<n+1;i++)
                A[i]=A[i-2]+2*A[i-1];
            for(i=0;i<n;i++)
            {
                B[i]=(float)A[i]/A[i+1];
                Fraction[0, i] = A[i];
                Fraction[1, i] = A[i+1];
            }
            for(i=0;i<n-1;i++)
            {
                for(j=(pos=i)+1;j<n;j++)
                    if(B[j]<B[pos])
                        pos=j;
                if(i!=pos)
                {
                    ftemp =B[pos];
                    B[pos]=B[i];
                    B[i]=ftemp;

                    temp=Fraction[0,pos];
                    Fraction [0,pos]=Fraction [0,i];
                    Fraction [0,i]=temp ;

                    temp=Fraction [1,pos];
                    Fraction [1,pos]=Fraction [1,i];
                    Fraction [1,i]=temp;
                }
            }

            for(i=0;i<n;i++)
                Console .Write ("{0}/{1}  ",Fraction [0,i],Fraction [1,i]);
            Console .Read();

        }
    }
}
抓图的结果:
 
实验三:C#面向对象程序基础
实验目的:
1. 加深理解面向对象编程的概念,如类、对象、实例化等;
2. 熟练掌握类的声明格式,特别是类的成员定义,构造函数,初始化对象等;
3. 熟练掌握方法的声明,理解并学会使用方法的参数传递,方法的重载等
实验内容:
实验3-1:阅读程序
相关程序代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY3_1
{
    class Program
    {
        class CRect
        {
            private int top, bottom, left, right;
            public static int total_rects = 0;
            public static long total_rect_area = 0;

            public CRect()
            {
                left = top = right = bottom = 0;
                total_rects++;
                total_rect_area += getHeight() * getWidth();
                Console.WriteLine("CRect()Contructing rectangle number{0}", total_rects);
                Console.WriteLine("Total rectangle areas is:{0}", total_rect_area);

            }
            public CRect(int x1, int y1, int x2, int y2)
            {
                left = x1;
                top = y1;
                right = x2;
                bottom = y2;
                total_rects++;
                total_rect_area += getHeight() * getWidth();
                Console.WriteLine("CRect(int,int,int ,int)Constructing rectangle number{0}", total_rects);
                Console.WriteLine("Total rectangle areas is :{0}", total_rect_area);
            }
            public CRect(CRect r)
            {
                left = r.left;
                right = r.right;
                top = r.top;
                bottom = r.bottom;
                total_rects++;
                total_rect_area += getHeight() * getWidth();
                Console.WriteLine("CRect(CRect&)Constructing rectangle number{0}", total_rects);
                Console.WriteLine("Total rectangle areas is :{0}", total_rect_area);

            }

            public int getHeight()
            {
                return (top > bottom ? top - bottom : bottom - top);
            }

            public int getWidth()
            {
                return right > left ? right - left : left - right;

            }

            public static int getTotalRects()
            {
                return total_rects;
            }

            public static long getTotalRectangle()
            {
                return total_rect_area;
            }
        }

        public class Test3_1
        {
            static void Main(string[] args)
            {
                CRect rect1 = new CRect(1, 3, 6, 4), rect2 = new CRect(rect1);//拷贝构造,通过重载
                Console.Write("Rectangle 2:Height:{0}", rect2.getHeight());
                Console.WriteLine(",Width:{0}", rect2.getWidth());
                {
                    CRect rect3 = new CRect();
                    Console.Write("Rectangle 3:Height:{0}", rect3.getHeight());
                    Console.WriteLine(",Width:{0}", rect3.getWidth());
                }

                Console.Write("Total_rects={0}", CRect.total_rects);
                Console.WriteLine(",total_rect_area={0}", CRect.total_rect_area);
                Console.Read();

            }
        }
    }
}
抓图的结果:
 
实验3-2:设计一个图书卡片类Card,用来保存图书馆卡片分类记录。这个类的成员包括书名、作者、馆藏数量。至少提供两个方法,store书的入库处理,show显示图书信息,程序运行时,可以从控制台上输入需要入库图书的总量,根据这个总数创建Card对象数组,然后输入数据,最后可以选择按书名、作者、入库量排序
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY3_2
{
   
        class Card
        {
            private string title, author;
            private int total;
            public Card()
            {
                title = "";
                author = "";
                total = 0;
            }
            public Card(string title, string author, int total)
            {
                this.title = title;
                this.author = author;
                this.total = total;
            }

            public void store(ref Card card)//使用ref关键字进行引用传递,似乎是它的拷贝构造
            {
                title = card.title;
                author = card.author;
                total = card.total;
            }

            public void show()
            {
                Console.WriteLine("Title:{0},Author:{1},Total:{2}", title, author, total);

            }

            public string Title//Title的属性可读可写
            {
                get { return title; }
                set { title = value; }
            }

            public string Author
            {
                get { return author; }
                set { author = value; }
            }

            public string Total
            {
                get { return Total; }
                set { total = int.Parse (value); }
            }
        }

        public class Test3_2
        {

            static void Main(string[] args)
            {
                Test3_2 T = new Test3_2();
                Card[] books;
                int[] index;
                int i, k;
                Card card = new Card();
                Console.Write("请输入需要入库图书的总数:");
                string sline = Console.ReadLine();
                int num = int.Parse(sline);
                books = new Card[num];
                for (i = 0; i < num; i++)
                    books [i]= new Card();
                index = new int[num];
                for (i = 0; i < num; i++)
                {
                    Console.Write("请输入书名:");
                    card.Title = Console.ReadLine();
                    Console.Write("请输入作者:");
                    card.Author = Console.ReadLine();
                    Console.Write("请输入入库量:");
                    sline = Console.ReadLine();
                    card.Total = sline;
                    books[i].store(ref card);
                    index[i] = i;//应该表示第几本书
                }

                Console.Write("请选择按什么关键字排序(1.按书名,2.按作者,3.按入库量)");
                sline = Console.ReadLine();
                int choice = int.Parse(sline);
                switch (choice)
                {
                    case 1:
                        T.sortTitle(books,index);
                        break;
                    case  2:
                        T.sortAuthor(books,index);
                        break;
                    case 3:
                        T.sortTotal(books,index);
                        break;

                }

                for (i = 0; i < num; i++)
                {
                    k = index[i];
                    books [k].show();//和给出的程序不同
                }
                Console .Read ();
            }

            void sortTitle(Card[] book, int[] index)
            {
                int i, j, m, n, temp;
                for (m = 0; m < index.Length - 1; m++)
                {
                    for (n = 0; n < index.Length- m - 1; n++)
                    {
                        i = index[n];
                        j = index[n + 1];
                        if (string.Compare(book[i].Title, book[j].Title) > 0)
                        {
                            temp = index[n];
                            index[n] = index[n + 1];
                            index[n + 1] = temp;
                        }
                    }
                }


            }

            void sortAuthor(Card[] book, int[] index)
            {
                int i, j, m, n, temp;
                for(m=0;m<index .Length -1;m++)
                    for (n = 0; n < index.Length -m- 1; n++)
                    {
                        i = index[n];
                        j = index[n + 1];
                        if (string.Compare(book[i].Author, book[j].Author) > 0)
                        {
                            temp = index[n];
                            index[n] = index[n+ 1];
                            index[n + 1] = temp;
                        }
                    }
            }

            void sortTotal(Card[] book, int[] index)
            {
                int i, j, m, n, temp;
                for (m = 0; m < index.Length - 1; m++)
                    for (n = 0; n < index.Length - m - 1;n++ )
                    {
                        i = index[n];
                        j = index[n + 1];
                        if (int.Parse (book[i].Total) > int.Parse (book[j].Total))
                        {
                            temp = index[n];
                            index[n] = index[n + 1];
                            index[n + 1] = temp;
                        }
                    }

            }
        }
   
}
抓图的结果:
 
实验3-3:假设某银行共发出M张储蓄卡,每张储蓄卡拥有唯一的卡号,每天每张储蓄卡至多支持储蓄卡持有者的N笔“存款”或“取款”业务。根据实际发生的业务,实际处理数据,以反映最新情况。
设Card卡包含的数据域有:卡号,当前余额,允许当日发生的业务次数(定义成静态变量,为所有Card类所共享),当日实际发生的业务数以及一个数组记录发生的具体业务,它提供的主要方法是store,处理判断是否超过当日允许发生的最大笔数,当前余额是否足以取款以及实现修改当前数据等。
当持卡者输入正确的卡号、存款或取款金额后,程序进行相应的处理。若是输入了不正确的数据,程序会提示持卡者重新输入;若输入的卡号为负数时,银行终止当日业务。
相关主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace SY3_3
{
    class Program
    {
        class Card
        {
            public long cardNo;//卡号
            decimal balance;//余额
            int currentNum;//当日业务实际发生笔数
            static int number;//每张卡允许当日存款或取款的总次数
            decimal[] currentMoney;//存放 当日存款金额,正值代表存款,负值代表取款
            public Card()
            {
                currentMoney = new decimal[number];

            }

            public Card(long No, decimal Balance)
            {
                cardNo = No;
                balance = Balance;
                currentMoney = new decimal[number];
            }

            public void store(decimal Money, out int status)
            {
                if (currentNum == number)
                {
                    status = 0;
                    return;//本卡已达当日允许的业务次数
                }
                if (balance + Money < 0)
                {
                    status = -1;
                    return;
                }

                currentMoney[currentNum] = Money;
                balance += Money;
                currentNum++;
                status = 1;
            }

            public void show()
            {
                Console.WriteLine("卡号:{0},当前余额:{1},当日发生业务的次数:{2}", cardNo, balance, currentNum);
                for (int i = 0; i < currentNum; i++)
                    Console.WriteLine("当时存款/取款的情况:{0}", currentMoney[i]);
            }

            static public int Number//设置允许当日存款或取款的总次数
            {
                set
                {
                    number = value;
                }
            }

            public long  CardNo
            {
                get
                {
                   return cardNo ;
                }
            }

        }

    public class Test3_3
    {
        static void Main(string[] args)
        {
            Test3_3 T=new Test3_3 ();
            Card []person;
            int Num,status,k;
            long CardNo;
            decimal Balance,Money;
            Console .Write ("请输入允许当日存款或取款的总次数:");
            string sline=Console.ReadLine();
            Card.Number=int .Parse (sline);
            Console .Write ("请输入某银行发出的储蓄卡总数:");
            sline =Console .ReadLine ();
            Num=int .Parse (sline);
            person =new Card [Num];
            for(int i=0;i<Num;i++)//初始化Num个存储卡 的卡号等信息
            {
                 Console .Write ("请输入卡号:");
                sline =Console .ReadLine ();
                CardNo =long .Parse (sline );
                Console .Write ("请输入{0}账户余额:",CardNo );
                sline=Console .ReadLine ();
                Balance =decimal .Parse (sline);
                person[i]=new Card (CardNo,Balance );
            }

            while(true)//进行存取款 业务处理
            {
                Console .WriteLine ("现在正进行存款取款的业务处理,如果输入的卡号<0,则结束业务处理");
                Console .Write ("请输入卡号:");
                sline=Console .ReadLine ();
                CardNo =long .Parse (sline );
                if(CardNo <0)
                    break ;
                k=T.Locate(person ,CardNo );
                if(k==-1)
                {
                    Console .WriteLine ("对不起,不存在{0}号的存储卡",CardNo );
                    continue ;
                }
                Console .WriteLine ("请输入卡金额(正值代表存款,负值代表取款):");
                sline =Console .ReadLine ();
                Money =decimal .Parse (sline );
                person [k].store (Money,out status );
                switch (status )
                {
                    case -1:
                        Console .WriteLine ("存款余额不足,不能完成本次的取款业务");
                        break;
                    case 0:
                        Console .WriteLine ("本卡已达当日允许的业务次数");
                        break;
                    case 1:
                        Console .WriteLine ("成功处理完当前业务");
                        person [k].show ();
                        break ;
                }

            }

        }

        int Locate(Card[]person,long CardNo)
        {
            int i;
            for (i = 0; i < person.Length; i++)
                if (person[i].cardNo == CardNo)
                    return i;
            return -1;
        }
    }
    }
}
抓图结果:
 
实验四:接口
实验目的:
1) 熟练掌握接口的定义和实现
2) 熟悉集合接口的使用
实验内容:
实验4-1:编写IEnglishDimensions和IMctricDimensions两个接口,同时以公制单位和英制单位显示框的尺寸。Box类继承IEnglishDimensions和IMctricDimensions两个接口,它们表示不同的度量衡系统。两个接口有相同的成员名Length和Width
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace jiekou
{
    class Program
    {
        interface IEnglishDimensions
        {
            float Length();
            float Width();
        }
        interface IMetricDimensions
        {
            float Length();
            float Width();
        }
        class Box : IEnglishDimensions, IMetricDimensions
        {
            float lengthInches;
            float widthInches;
            public Box(float length, float width)
            {
                lengthInches = length;
                widthInches = width;
            }
            float IEnglishDimensions.Length()
            {
                return lengthInches;
            }
            float IEnglishDimensions.Width()
            {
                return widthInches;
            }
            float IMetricDimensions.Length()
            {
                return lengthInches * 2.54f;
            }
            float IMetricDimensions.Width()
            {
                return widthInches * 2.54f;
            }
        }
        static void Main(string[] args)
        {
            Box myBox = new Box(30.0f, 20.0f);
            IEnglishDimensions eDimensions = (IEnglishDimensions)myBox;
            IMetricDimensions mDimensions = (IMetricDimensions)myBox;
            System.Console.WriteLine("Length(in):{0}", eDimensions.Length());
            System.Console.WriteLine("Width(in):{0}", eDimensions.Width());
            System.Console.WriteLine("Length(out):{0}", mDimensions.Length());
            System.Console.WriteLine("Width(out):{0}", mDimensions.Width());

        }
    }
}
抓图的结果:
 
实验4-2:考虑这样一个水果篮(FruitBasket),里面至多可以装有10个苹果(Apple)和香蕉(Bananas),它们都派生自一个叫水果(Fruit)的基类。使用集合接口IEnumerable和Ienumerator实现装入水果过程及遍历水果。
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace 试验4__2
{
    public class Frult
    {
        public virtual string Name
        {
            get { return ("Frult"); }
        }
    }
    public class Apple : Frult
    {
        public override string Name
        {
            get
            {
                return ("Apple");
            }
        }
    }
    public class Banana : Frult
    {
        public override string Name
        {
            get
            {
                return ("Banana");
            }
        }
    }
    public class FrultBasket : IEnumerable
    {
        static int Max = 10;
        Frult[] basket = new Frult[Max];
        int count = 0;
        internal Frult this[int index]
        {
            get { return (basket[index]); }
            set { basket[index] = value; }
        }
        internal int Count
        {
            get { return (count); }
        }
        public void Add(Frult frult)
        {
            if (count > Max)
            {
                Console.WriteLine("超出水果筐容量!");
            }
            basket[count++] = frult;
        }
        public IEnumerator GetEnumerator()
        {
            return (new FrultBasketEnumerator(this));
        }
    }
    public class FrultBasketEnumerator : IEnumerator
    {
        FrultBasket frultBasket;
        int index;
        public void Reset()
        {
            index = -1;
        }
        public object Current
        {
            get { return (frultBasket[index]); }
        }
        public bool MoveNext()
        {
            if (++index >= frultBasket.Count)
                return false;
            else
                return true;
        }
        internal FrultBasketEnumerator(FrultBasket frultBasket)
        {
            this.frultBasket = frultBasket;
            Reset();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            FrultBasket frultBasket = new FrultBasket();
            Console.WriteLine("Adding a Banana");
            frultBasket.Add(new Banana());
            Console.WriteLine("Adding a Apple");
            frultBasket.Add(new Apple());
            Console.WriteLine("");
            Console.WriteLine("The basket is holding!");
            foreach (Frult frult in frultBasket)
            {
                Console.WriteLine("a(n)" + frult.Name);
            }
            Console.Read();
        }
    }
}

抓图的结果:
 
实验五:异常处理
实验目的:
1) 理解异常的产生过程和异常处理的概念
2) 掌握C#异常处理的方法
实验内容:
实验5-1:输入1-365之间的数字,判断它是一年中的几月几日
相关的主要代码:
using System;
using System.Collections.Generic;
using System.Text;

enum MonthName
{ January,February,March,April,May,June,July,August,September,October,November,December}


namespace SY5_1
{
    class WhatDay
    {
        static void Main(string[] args)
        {
            try
            {
                Console.Write("Please input a day number between 1 and 365:");
                string line = Console.ReadLine();
                int dayNum = int.Parse(line);
                if (dayNum < 1 || dayNum > 365)
                {
                    throw new ArgumentOutOfRangeException("Day out of Range!");//使用throw语句,是进行无条件抛出异常
                }
                int monthNum = 0;
                foreach (int daysInMonth in DaysInMonths)
                {
                    if (dayNum <= daysInMonth)
                    {
                        break;
                    }
                    else
                    {
                        dayNum -= daysInMonth;
                        monthNum++;
                    }
                }
                MonthName temp = (MonthName)monthNum;
                string monthName = Enum.Format(typeof(MonthName), temp, "g");//将指定枚举类型的指定值转换为与其等效的字符串表示形式
                Console .WriteLine ("{0}  {1}",dayNum ,monthName );
            }
            catch (Exception caught)
            {
                Console .WriteLine (caught );
            }
            Console.Read();
        }
  
        static System.Collections.ICollection DaysInMonths = new int[12] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
      
    }
}
抓图的结果:
 
实验六:Windows应用程序开发
实验目的:
1) 掌握建立Windows应用程序的步骤和方法;
2) 掌握使用Windows Forms控件,菜单和对话框的使用
3) 掌握控件及其使用方法
实验内容:
实验6-1:创建窗体与菜单练习
相关的主要代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void menuStrip3_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            private void MenuStrip_Close_Clock(object sender,EventArgs e)
            {
               this.Close();
            }
        }
    }
}

抓图的结果:
    
使用文件->打开可以打开一个对话框,如下图:
 
实验6-2:练习使用按钮、单选按钮和复选框等窗体控件
相关的主要代码:
1. MyForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace 试验6__2
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
        }

        private void checkBox_lv_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_lan_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void MyForm_Load(object sender, EventArgs e)
        {

        }

        private void radioButton_hong_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButton_hong.Checked == true)
                this.BackColor = Color.Red;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void checkBox_hong_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox_hong.Checked == true)
                this.textBox1.Text = textBox1.Text + checkBox_hong.Text + ",";
        }

        private void radioButton_lv_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButton_lv.Checked == true)
                this.BackColor = Color.Green;
        }

        private void radioButton_lan_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButton_lan.Checked == true)
                this.BackColor = Color.Blue;

        }

        private void checkBox_lv_CheckedChanged_1(object sender, EventArgs e)
        {
            if (this.checkBox_lv.Checked ==true)
                this.textBox1.Text = textBox1.Text + checkBox_lv.Text + ",";
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void checkBox_lan_CheckedChanged_1(object sender, EventArgs e)
        {
            if (this.checkBox_lan.Checked == true)
                this.textBox1.Text = textBox1.Text + checkBox_lan.Text + ",";
        }

        private void checkBox_cheng_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox_cheng.Checked == true)
                this.textBox1.Text = textBox1.Text + checkBox_cheng.Text + ",";
        }

        private void checkBox_huang_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox_huang.Checked == true)
                this.textBox1.Text = textBox1.Text + checkBox_huang.Text + ",";
        }

        private void checkBox_zi_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox_zi.Checked == true)
                this.textBox1.Text = textBox1.Text + checkBox_zi.Text + ",";
        }

        private void radioButton_hong_CheckedChanged_1(object sender, EventArgs e)
        {
            if (this.radioButton_hong.Checked == true)
                this.BackColor = Color.Red;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
2. MyForm.Designer.cs
namespace 试验6__2
{
    partial class MyForm
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.radioButton_hong = new System.Windows.Forms.RadioButton();
            this.radioButton_lv = new System.Windows.Forms.RadioButton();
            this.radioButton_lan = new System.Windows.Forms.RadioButton();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.checkBox_zi = new System.Windows.Forms.CheckBox();
            this.checkBox_huang = new System.Windows.Forms.CheckBox();
            this.checkBox_cheng = new System.Windows.Forms.CheckBox();
            this.checkBox_lan = new System.Windows.Forms.CheckBox();
            this.checkBox_lv = new System.Windows.Forms.CheckBox();
            this.checkBox_hong = new System.Windows.Forms.CheckBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            //
            // radioButton_hong
            //
            this.radioButton_hong.AutoSize = true;
            this.radioButton_hong.Location = new System.Drawing.Point(6, 21);
            this.radioButton_hong.Name = "radioButton_hong";
            this.radioButton_hong.Size = new System.Drawing.Size(35, 16);
            this.radioButton_hong.TabIndex = 4;
            this.radioButton_hong.TabStop = true;
            this.radioButton_hong.Text = "红";
            this.radioButton_hong.UseVisualStyleBackColor = true;
            this.radioButton_hong.CheckedChanged += new System.EventHandler(this.radioButton_hong_CheckedChanged_1);
            //
            // radioButton_lv
            //
            this.radioButton_lv.AutoSize = true;
            this.radioButton_lv.Location = new System.Drawing.Point(6, 64);
            this.radioButton_lv.Name = "radioButton_lv";
            this.radioButton_lv.Size = new System.Drawing.Size(35, 16);
            this.radioButton_lv.TabIndex = 5;
            this.radioButton_lv.TabStop = true;
            this.radioButton_lv.Text = "绿";
            this.radioButton_lv.UseVisualStyleBackColor = true;
            this.radioButton_lv.CheckedChanged += new System.EventHandler(this.radioButton_lv_CheckedChanged);
            //
            // radioButton_lan
            //
            this.radioButton_lan.AutoSize = true;
            this.radioButton_lan.Location = new System.Drawing.Point(6, 113);
            this.radioButton_lan.Name = "radioButton_lan";
            this.radioButton_lan.Size = new System.Drawing.Size(35, 16);
            this.radioButton_lan.TabIndex = 6;
            this.radioButton_lan.TabStop = true;
            this.radioButton_lan.Text = "蓝";
            this.radioButton_lan.UseVisualStyleBackColor = true;
            this.radioButton_lan.CheckedChanged += new System.EventHandler(this.radioButton_lan_CheckedChanged);
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.radioButton_hong);
            this.groupBox1.Controls.Add(this.radioButton_lan);
            this.groupBox1.Controls.Add(this.radioButton_lv);
            this.groupBox1.Location = new System.Drawing.Point(12, 2);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(145, 144);
            this.groupBox1.TabIndex = 3;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "背景颜色";
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.checkBox_zi);
            this.groupBox2.Controls.Add(this.checkBox_huang);
            this.groupBox2.Controls.Add(this.checkBox_cheng);
            this.groupBox2.Controls.Add(this.checkBox_lan);
            this.groupBox2.Controls.Add(this.checkBox_lv);
            this.groupBox2.Controls.Add(this.checkBox_hong);
            this.groupBox2.Location = new System.Drawing.Point(176, 2);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(213, 144);
            this.groupBox2.TabIndex = 4;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "你喜欢的颜色";
            this.groupBox2.Enter += new System.EventHandler(this.groupBox2_Enter);
            //
            // checkBox_zi
            //
            this.checkBox_zi.AutoSize = true;
            this.checkBox_zi.Location = new System.Drawing.Point(106, 113);
            this.checkBox_zi.Name = "checkBox_zi";
            this.checkBox_zi.Size = new System.Drawing.Size(36, 16);
            this.checkBox_zi.TabIndex = 6;
            this.checkBox_zi.Text = "紫";
            this.checkBox_zi.UseVisualStyleBackColor = true;
            this.checkBox_zi.CheckedChanged += new System.EventHandler(this.checkBox_zi_CheckedChanged);
            //
            // checkBox_huang
            //
            this.checkBox_huang.AutoSize = true;
            this.checkBox_huang.Location = new System.Drawing.Point(106, 64);
            this.checkBox_huang.Name = "checkBox_huang";
            this.checkBox_huang.Size = new System.Drawing.Size(36, 16);
            this.checkBox_huang.TabIndex = 5;
            this.checkBox_huang.Text = "黄";
            this.checkBox_huang.UseVisualStyleBackColor = true;
            this.checkBox_huang.CheckedChanged += new System.EventHandler(this.checkBox_huang_CheckedChanged);
            //
            // checkBox_cheng
            //
            this.checkBox_cheng.AutoSize = true;
            this.checkBox_cheng.Location = new System.Drawing.Point(106, 21);
            this.checkBox_cheng.Name = "checkBox_cheng";
            this.checkBox_cheng.Size = new System.Drawing.Size(36, 16);
            this.checkBox_cheng.TabIndex = 4;
            this.checkBox_cheng.Text = "橙";
            this.checkBox_cheng.UseVisualStyleBackColor = true;
            this.checkBox_cheng.CheckedChanged += new System.EventHandler(this.checkBox_cheng_CheckedChanged);
            //
            // checkBox_lan
            //
            this.checkBox_lan.AutoSize = true;
            this.checkBox_lan.Location = new System.Drawing.Point(6, 114);
            this.checkBox_lan.Name = "checkBox_lan";
            this.checkBox_lan.Size = new System.Drawing.Size(36, 16);
            this.checkBox_lan.TabIndex = 3;
            this.checkBox_lan.Text = "蓝";
            this.checkBox_lan.UseVisualStyleBackColor = true;
            this.checkBox_lan.CheckedChanged += new System.EventHandler(this.checkBox_lan_CheckedChanged_1);
            //
            // checkBox_lv
            //
            this.checkBox_lv.AutoSize = true;
            this.checkBox_lv.Location = new System.Drawing.Point(6, 65);
            this.checkBox_lv.Name = "checkBox_lv";
            this.checkBox_lv.Size = new System.Drawing.Size(36, 16);
            this.checkBox_lv.TabIndex = 2;
            this.checkBox_lv.Text = "绿";
            this.checkBox_lv.UseVisualStyleBackColor = true;
            this.checkBox_lv.CheckedChanged += new System.EventHandler(this.checkBox_lv_CheckedChanged_1);
            //
            // checkBox_hong
            //
            this.checkBox_hong.AutoSize = true;
            this.checkBox_hong.Location = new System.Drawing.Point(6, 20);
            this.checkBox_hong.Name = "checkBox_hong";
            this.checkBox_hong.Size = new System.Drawing.Size(36, 16);
            this.checkBox_hong.TabIndex = 1;
            this.checkBox_hong.Text = "红";
            this.checkBox_hong.UseVisualStyleBackColor = true;
            this.checkBox_hong.CheckedChanged += new System.EventHandler(this.checkBox_hong_CheckedChanged);
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(12, 152);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(403, 102);
            this.textBox1.TabIndex = 5;
            this.textBox1.Text = "你喜欢的颜色:";
            this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(340, 277);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 6;
            this.button1.Text = "退出";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // MyForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(427, 312);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Name = "MyForm";
            this.Text = "MyForm";
            this.Load += new System.EventHandler(this.MyForm_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.RadioButton radioButton_hong;
        private System.Windows.Forms.RadioButton radioButton_lv;
        private System.Windows.Forms.RadioButton radioButton_lan;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.CheckBox checkBox_zi;
        private System.Windows.Forms.CheckBox checkBox_huang;
        private System.Windows.Forms.CheckBox checkBox_cheng;
        private System.Windows.Forms.CheckBox checkBox_lan;
        private System.Windows.Forms.CheckBox checkBox_lv;
        private System.Windows.Forms.CheckBox checkBox_hong;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
    }
}
抓图的结果:
 
实验6-3:练习使用控件、文本框控件、;列表控件和组合框控件等窗体控件
相关主要代码:
1. Form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication6_3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox_Book.SelectedIndex != -1)
            {
                listBox_Book.Items.Remove(this.listBox_Book.SelectedItem);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox_Book.Items.Add("书名:"+textBox_Bookname.Text+",出版社:"+comboBox_Publishing.Text);
            textBox_Bookname.Text = "";
        }
    }
}
2. Form1.Designer.cs
namespace WindowsApplication6_3
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.textBox_Bookname = new System.Windows.Forms.TextBox();
            this.comboBox_Publishing = new System.Windows.Forms.ComboBox();
            this.button_Add = new System.Windows.Forms.Button();
            this.button_Remove = new System.Windows.Forms.Button();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.listBox_Book = new System.Windows.Forms.ListBox();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 2;
            this.label1.Text = "输入书名";
            this.label1.Click += new System.EventHandler(this.label1_Click);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(1, 100);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 4;
            this.label2.Text = "选择出版社";
            this.label2.Click += new System.EventHandler(this.label2_Click);
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.comboBox_Publishing);
            this.groupBox1.Controls.Add(this.textBox_Bookname);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Location = new System.Drawing.Point(2, 3);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(124, 180);
            this.groupBox1.TabIndex = 8;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "groupBox1";
            //
            // textBox_Bookname
            //
            this.textBox_Bookname.Location = new System.Drawing.Point(3, 32);
            this.textBox_Bookname.Name = "textBox_Bookname";
            this.textBox_Bookname.Size = new System.Drawing.Size(100, 21);
            this.textBox_Bookname.TabIndex = 3;
            //
            // comboBox_Publishing
            //
            this.comboBox_Publishing.FormattingEnabled = true;
            this.comboBox_Publishing.Items.AddRange(new object[] {
            "清华大学出版社",
            "电子工业出版社",
            "中国铁道出版社",
            "机械工业出版社",
            "人民邮电出版社",
            "中国电力出版社"});
            this.comboBox_Publishing.Location = new System.Drawing.Point(0, 115);
            this.comboBox_Publishing.Name = "comboBox_Publishing";
            this.comboBox_Publishing.Size = new System.Drawing.Size(121, 20);
            this.comboBox_Publishing.TabIndex = 1;
            this.comboBox_Publishing.Text = "未知";
            //
            // button_Add
            //
            this.button_Add.Location = new System.Drawing.Point(25, 42);
            this.button_Add.Name = "button_Add";
            this.button_Add.Size = new System.Drawing.Size(75, 23);
            this.button_Add.TabIndex = 5;
            this.button_Add.Text = "添加>>";
            this.button_Add.UseVisualStyleBackColor = true;
            this.button_Add.Click += new System.EventHandler(this.button1_Click);
            //
            // button_Remove
            //
            this.button_Remove.Location = new System.Drawing.Point(25, 100);
            this.button_Remove.Name = "button_Remove";
            this.button_Remove.Size = new System.Drawing.Size(75, 23);
            this.button_Remove.TabIndex = 6;
            this.button_Remove.Text = "移出<<";
            this.button_Remove.UseVisualStyleBackColor = true;
            this.button_Remove.Click += new System.EventHandler(this.button2_Click);
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.button_Add);
            this.groupBox2.Controls.Add(this.button_Remove);
            this.groupBox2.Location = new System.Drawing.Point(154, 3);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(123, 180);
            this.groupBox2.TabIndex = 7;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "groupBox2";
            //
            // listBox_Book
            //
            this.listBox_Book.FormattingEnabled = true;
            this.listBox_Book.ItemHeight = 12;
            this.listBox_Book.Location = new System.Drawing.Point(301, 12);
            this.listBox_Book.Name = "listBox_Book";
            this.listBox_Book.Size = new System.Drawing.Size(220, 172);
            this.listBox_Book.TabIndex = 0;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(546, 258);
            this.Controls.Add(this.listBox_Book);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.ComboBox comboBox_Publishing;
        private System.Windows.Forms.TextBox textBox_Bookname;
        private System.Windows.Forms.Button button_Add;
        private System.Windows.Forms.Button button_Remove;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.ListBox listBox_Book;
    }
}
抓图的结果:
 
 
实验七:GDI+编程
实验目的:
1) 创建Graphics对象;
2) 使用Graphics对象绘制线条和形状、呈现文本或显示与操作图像
实验内容:
实验7-1:创建Graphics对象,使用Graphics对象绘制线条和形状
主要相关代码:
1. 添加一个按钮,双击按钮,添加绘图程序
private void button1_Click(object sender, EventArgs e)
        {
            Graphics myGra = this.CreateGraphics();

            Pen mypen1 = new Pen(Color.Red, 2);
            myGra.DrawLine(mypen1, 100, 0, 300, 500);//直线

            Pen mypen2 = new Pen(Color.Orange, 2);
            myGra.DrawEllipse(mypen2, 100, 100, 60, 60);//圆形
            myGra.DrawEllipse(mypen2, 200, 100, 60, 120);//椭圆形

            Pen mypen3= new Pen(Color.Yellow , 3);
            myGra.DrawRectangle (mypen3, 123, 234, 60, 60);//正方形
            myGra.DrawRectangle(mypen3, 223, 234, 60, 120);//任意矩形

            //自定义多边形
            Point[] myPoint = new Point[4];
            myPoint[0].Y = 100;
            myPoint[1].X = 200;
            myPoint[1].Y = 20;
            myPoint[2].X = 300;
            myPoint[2].Y = 100;
            myPoint[3].X= 123;
            myPoint[3].Y = 234;
            Pen mypen20 = new Pen(Color.Aqua);
            myGra.DrawPolygon(mypen20, myPoint);

        }
2. 添加两个按钮,实现清除和文本测试
private void button3_Click(object sender, EventArgs e)
        {
            Graphics fontGra = this.CreateGraphics();
            Font myFont = new Font("楷体_GB2312", 24);
            Brush myBr = new SolidBrush(Color.Red);
            fontGra.DrawString(button_Font.Text, myFont, myBr, new Point(200, 200));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Graphics clearG = this.CreateGraphics();
            clearG.Clear(Color.White);
        }
抓图的结果:
  
实验7-2:操作图像,实现图片的打开、保存等功能
相关主要代码:
1.Form1.Designer.cs
namespace myImage
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.FileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemOpen = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemSave = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemExit = new System.Windows.Forms.ToolStripMenuItem();
            this.OpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemInvert = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemGray = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemBright = new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // menuStrip1
            //
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.FileToolStripMenuItem,
            this.OpToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(292, 24);
            this.menuStrip1.TabIndex = 0;
            this.menuStrip1.Text = "menuStrip1";
            //
            // FileToolStripMenuItem
            //
            this.FileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.menuItemOpen,
            this.menuItemSave,
            this.menuItemExit});
            this.FileToolStripMenuItem.Name = "FileToolStripMenuItem";
            this.FileToolStripMenuItem.Size = new System.Drawing.Size(43, 20);
            this.FileToolStripMenuItem.Text = "文件";
            //
            // menuItemOpen
            //
            this.menuItemOpen.Name = "menuItemOpen";
            this.menuItemOpen.Size = new System.Drawing.Size(152, 22);
            this.menuItemOpen.Text = "打开";
            //
            // menuItemSave
            //
            this.menuItemSave.Name = "menuItemSave";
            this.menuItemSave.Size = new System.Drawing.Size(152, 22);
            this.menuItemSave.Text = "保存";
            //
            // menuItemExit
            //
            this.menuItemExit.Name = "menuItemExit";
            this.menuItemExit.Size = new System.Drawing.Size(152, 22);
            this.menuItemExit.Text = "退出";
            //
            // OpToolStripMenuItem
            //
            this.OpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.menuItemInvert,
            this.menuItemGray,
            this.menuItemBright});
            this.OpToolStripMenuItem.Name = "OpToolStripMenuItem";
            this.OpToolStripMenuItem.Size = new System.Drawing.Size(43, 20);
            this.OpToolStripMenuItem.Text = "操作";
            //
            // menuItemInvert
            //
            this.menuItemInvert.Name = "menuItemInvert";
            this.menuItemInvert.Size = new System.Drawing.Size(152, 22);
            this.menuItemInvert.Text = "插入";
            //
            // menuItemGray
            //
            this.menuItemGray.Name = "menuItemGray";
            this.menuItemGray.Size = new System.Drawing.Size(152, 22);
            this.menuItemGray.Text = "灰度";
            //
            // menuItemBright
            //
            this.menuItemBright.Name = "menuItemBright";
            this.menuItemBright.Size = new System.Drawing.Size(152, 22);
            this.menuItemBright.Text = "亮度";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 267);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "Form1";
            this.Text = "Form1";
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
       
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem FileToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem menuItemOpen;
        private System.Windows.Forms.ToolStripMenuItem menuItemSave;
        private System.Windows.Forms.ToolStripMenuItem menuItemExit;
        private System.Windows.Forms.ToolStripMenuItem OpToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem menuItemInvert;
        private System.Windows.Forms.ToolStripMenuItem menuItemGray;
        private System.Windows.Forms.ToolStripMenuItem menuItemBright;
    }
}
2.Form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


namespace myImage
{
    public partial class Form1 : Form
    {
        public Bitmap m_Bitmap=null;
        public Form1()
        {
            InitializeComponent();
            //m_Bitmap = new Bitmap(@"C:\A.bmp");
        }

        private void FileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void menuItemOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Bitmap文件(*.bmp)|*.bmp|Jpeg文件(*.Jpg)|*.jpg|所有合适的文件(*.bmp/*.jpg)|*.bmp/*.jpg";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;
            if (DialogResult.OK == openFileDialog.ShowDialog())
            {
                m_Bitmap= (Bitmap)Bitmap.FromFile(openFileDialog .FileName,false);
                this.AutoScroll = true;
                this.AutoScrollMinSize = new Size((int)(m_Bitmap.Width), (int)m_Bitmap.Height);
                this.Invalidate();
            }
        }

        private void menuItemSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Bitmap文件(*.bmp)|*.bmp|Jpeg文件(*.Jpg)|*.jpg|所有合适的文件(*.bmp/*.jpg)|*.bmp/*.jpg";
            saveFileDialog.FilterIndex = 1;
            saveFileDialog.RestoreDirectory = true;
            if (DialogResult.OK == saveFileDialog.ShowDialog())
            {
               m_Bitmap.Save(saveFileDialog.FileName);
            }
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics gra = e.Graphics;
            gra.DrawImage(m_Bitmap,new Rectangle(this.AutoScrollPosition.X,this.AutoScrollPosition.Y,(int)(m_Bitmap.Width),(int)(m_Bitmap.Height)));
        }
    }
}
抓图的结果
 
实验八:文件和数据库应用
实验目的:
1) 熟悉文件的基本功能和综合应用方法;
2) 熟悉数据库基本功能,关系数据库的参照完整性与SQL语言的使用;
3) 掌握C#数据库应用的基本方法
实验内容:
实验8-1:
(1) 按教材6.3文件综合应用实例要求,设计界面,加入代码
(2) 运行后进行操作,检验程序功能
主要相关代码:
1. frmMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace FileProject
{
    public partial class frmMain : Form
    {
        public string m_Address = @"C:\A";
        public string m_FileName;
        public frmMain()
        {
            InitializeComponent();
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void FillList()
        {
            lstFile.Clear();
            foreach (string m_FileName in Directory.GetFiles(m_Address))
            {
                string m_Name = m_FileName.Substring(m_Address.Length + 1, m_FileName.Length - m_Address.Length - 1);
                ListViewItem m_Item = lstFile.Items.Add(m_Name);
                m_Item.ImageIndex = 0;
            }
            return;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            FillList();
        }
       

        private void btnCreat_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Trim() == string.Empty) return;
            string m_Path = m_Address + @"\" + txtName.Text.Trim();
            FileInfo m_FileInfo = new FileInfo(m_Path);
            m_FileInfo.Create();
            FillList();
            return;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstFile.SelectedItems.Count < 1) return;
            foreach (ListViewItem m_Item in lstFile.SelectedItems)
            {
                string m_Path = m_Address + @"\" + m_Item.Text;
                File.Delete(m_Path);
            }
            FillList();
            return;
        }

        private void btnRename_Click(object sender, EventArgs e)
        {
            if (lstFile.SelectedItems.Count != 1) return;
            string m_PathOld = m_Address + @"\" + lstFile.SelectedItems[0].Text;
            string m_PathNew = m_Address + @"\" + txtName.Text.Trim();
            if (File.Exists(m_PathNew))
            {
                MessageBox.Show("已存在同名文件");
                return;
            }
            else
            {
                FileInfo m_FileInfo = new FileInfo(m_PathOld);
                m_FileInfo.MoveTo(m_PathNew);
                FillList();
                return;
            }
        }

        private void listFile_DoubleClick(object sender, EventArgs e)
        {
            if (lstFile.SelectedItems.Count != 1) return;
            Process m_Process = new Process();
            string m_Path = m_Address + @"\" + lstFile.SelectedItems[0].Text;
            m_Process.StartInfo.FileName = m_Path;
            try
            {
                m_Process.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return;
        }
    }
}
2. frmMain.Designer.cs
namespace FileProject
{
    partial class frmMain
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
            this.lstFile = new System.Windows.Forms.ListView();
            this.btnCreat = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnRename = new System.Windows.Forms.Button();
            this.txtName = new System.Windows.Forms.TextBox();
            this.imgFile = new System.Windows.Forms.ImageList(this.components);
            this.SuspendLayout();
            //
            // lstFile
            //
            this.lstFile.LargeImageList = this.imgFile;
            this.lstFile.Location = new System.Drawing.Point(12, 12);
            this.lstFile.Name = "lstFile";
            this.lstFile.Size = new System.Drawing.Size(268, 171);
            this.lstFile.TabIndex = 0;
            this.lstFile.UseCompatibleStateImageBehavior = false;
            this.lstFile.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
            //
            // btnCreat
            //
            this.btnCreat.Location = new System.Drawing.Point(12, 225);
            this.btnCreat.Name = "btnCreat";
            this.btnCreat.Size = new System.Drawing.Size(76, 30);
            this.btnCreat.TabIndex = 1;
            this.btnCreat.Text = "创建";
            this.btnCreat.UseVisualStyleBackColor = true;
            this.btnCreat.Click += new System.EventHandler(this.btnCreat_Click);
            //
            // btnDelete
            //
            this.btnDelete.Location = new System.Drawing.Point(110, 225);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(79, 30);
            this.btnDelete.TabIndex = 2;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            //
            // btnRename
            //
            this.btnRename.Location = new System.Drawing.Point(207, 226);
            this.btnRename.Name = "btnRename";
            this.btnRename.Size = new System.Drawing.Size(73, 29);
            this.btnRename.TabIndex = 3;
            this.btnRename.Text = "重命名";
            this.btnRename.UseVisualStyleBackColor = true;
            this.btnRename.Click += new System.EventHandler(this.btnRename_Click);
            //
            // txtName
            //
            this.txtName.Location = new System.Drawing.Point(12, 189);
            this.txtName.Name = "txtName";
            this.txtName.Size = new System.Drawing.Size(268, 21);
            this.txtName.TabIndex = 4;
            this.txtName.DoubleClick += new System.EventHandler(this.listFile_DoubleClick);
            //
            // imgFile
            //
            this.imgFile.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgFile.ImageStream")));
            this.imgFile.TransparentColor = System.Drawing.Color.Transparent;
            this.imgFile.Images.SetKeyName(0, "FILER.ICO");
            //
            // frmMain
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 267);
            this.Controls.Add(this.txtName);
            this.Controls.Add(this.btnRename);
            this.Controls.Add(this.btnDelete);
            this.Controls.Add(this.btnCreat);
            this.Controls.Add(this.lstFile);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "FileProject";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ListView lstFile;
        private System.Windows.Forms.Button btnCreat;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnRename;
        private System.Windows.Forms.TextBox txtName;
        private System.Windows.Forms.ImageList imgFile;
    }
}
抓图的结果:
 
未解决的问题:
比较奇怪的问题是:如果直接在C盘上直接操作的话,只能实现创建的功能!其余的两个都不能实现!如果建立一个文件夹,那么这些操作在文件夹下都可以实现了。
实验8-2:建立一个简单的学生成绩浏览界面
主要相关代码:
1. 为窗体类添加一个控制按钮状态的方法:
private void ButtonStateControl()
        {
            btnFirst.Enabled = true;
            btnNext.Enabled = true;
            btnPrev.Enabled = true;
            btnLast.Enabled=true;
            if (this.BindingContext[mDataSet, "Student.Student_Course"].Position == 0)
            {
                btnPrev.Enabled = false;
                btnFirst.Enabled = false;
            }
            if (this.BindingContext[mDataSet, "Student.Student_Course"].Position ==
                (this.BindingContext[mDataSet, "Student.Student_Course"].Count - 1))
            {
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
        }
2. 由于在窗体打开时就需要设定按钮状态,所以在窗体的Load事件中调用此方法
private void Form2_Load(object sender, EventArgs e)
        {
            ButtonStateControl();
}
3. 对数据集导航的四个按钮进行编码实现记录指针的移动

        private void btnFirst_Click(object sender, EventArgs e)
        {
            this.BindingContext[mDataSet, "Student.Student_Course"].Position=0;
            ButtonStateControl();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            this.BindingContext[mDataSet, "Student.Student_Course"].Position -= 1;
            ButtonStateControl();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            this.BindingContext[mDataSet, "Student.Student_Course"].Position = this.BindingContext[mDataSet, "Student.Student_Course"].Count - 1;
            ButtonStateControl();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            this.BindingContext[mDataSet, "Student.Student_Course"].Position += 1;
            ButtonStateControl();
        }
4. 为主窗口Load事件添加代码
private void Form1_Load(object sender, EventArgs e)
        {
            daStudent.Fill(dataSet11);
            daScore.Fill(dataSet11);
            frmScore = new Form2();
            frmScore.mDataSet = dataSet11;
            frmScore.BindingContext = this.BindingContext;
            frmScore.txtCourse.DataBindings.Add("Text",dataSet11,"Student.Student_Course.课程名称");
            frmScore.txtScore.DataBindings.Add("Text", dataSet11, "Student.Student_Course.成绩");
            frmScore.Text = "成绩明细:" + dgStudent[dgStudent.CurrentCell.RowNumber,1].ToString();
        }
5. 当用户点击“查看成绩”按钮时弹出明细窗口,设置该按钮的事件处理代码
private void button1_Click(object sender, EventArgs e)
        {
            frmScore.ShowDialog(this);
}

抓图的结果:
 
 
未解决的问题:查询成绩的时候只能查找第一个学生的成绩,以后的都查不了

 

原创粉丝点击