C# WinForm 界面控件应用

C# WinForms (Windows Forms) 是一种用于创建 Windows 桌面应用程序的用户界面(UI)框架。它是 Microsoft .NET 平台的一部分,提供了一组用于构建 Windows 应用程序的类和控件。

在使用 C# WinForms 开发应用程序时,你需要创建一个 Windows 窗体应用程序项目,然后在该项目中添加窗体、控件和事件处理程序等。

按钮与编辑框的使用

这个示例的功能是在一个 WinForms 应用程序中实现了一个简单的进度条功能。当用户点击按钮时,程序会从用户输入的开始值和结束值中计算出一个数字范围,并通过循环递增进度条的值。在每次循环中,进度条的值增加 1,同时程序通过线程休眠模拟一些操作的时间消耗。这样用户就可以在界面上看到进度条的增长,以及操作的进度。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            int start = int.Parse(textBox1.Text);
            int end = int.Parse(textBox2.Text);

            for (int x = start; x < end; x++)
            {
                progressBar1.Value += 1;
                Thread.Sleep(100);
            }
        }
    }
}

listView 列表框

该代码是一个简单的 Windows Forms 应用程序,具有一个窗体(Form1)和一个按钮(button1)以及一个 ListView 控件(listView1)。

功能概述:

  • 在窗体加载时,通过添加三个列标题来配置 ListView 控件的列。
  • 当用户单击按钮时,将清除 ListView 控件中的所有项,并动态添加 100 个项。
  • 每个项包含一个图像索引和三列数据,其中第一列为 "UID",第二列为 "UNAME",第三列为 "UAGE",其中 "UAGE" 的值包含行数。
  • 使用 BeginUpdate 和 EndUpdate 方法来暂时挂起 UI 的更新,以提高性能并一次性绘制所有项。

这段代码的功能是在 ListView 控件中显示一个简单的数据列表,并在按钮点击时动态更新数据。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            ColumnHeader Uid = new ColumnHeader();

            Uid.Text = "UID";
            Uid.Width = 100;
            Uid.TextAlign = HorizontalAlignment.Left;
            this.listView1.Columns.Add(Uid);

            ColumnHeader Uname = new ColumnHeader();
            Uname.Text = "UNAME";
            Uname.Width = 100;
            Uname.TextAlign = HorizontalAlignment.Left;
            this.listView1.Columns.Add(Uname);

            ColumnHeader Uage = new ColumnHeader();
            Uage.Text = "UAGE";
            Uage.Width = 100;
            Uage.TextAlign = HorizontalAlignment.Left;
            this.listView1.Columns.Add(Uage);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 添加数据
            this.listView1.BeginUpdate();  //数据更新,UI暂时挂起
            this.listView1.Items.Clear(); //只移除所有的项。 
            for (int x = 0; x < 100; x++)
            {
                ListViewItem lv = new ListViewItem();
                lv.ImageIndex = x;
                lv.Text = "UUID -> " + x;

                lv.SubItems.Add("第2列");
                lv.SubItems.Add("第3列" + x + "行");
                this.listView1.Items.Add(lv);
            }
            this.listView1.EndUpdate();  //结束数据处理,UI界面一次性绘制。 
        }
    }
}

MID 窗体设计

该代码是一个简单的 Windows Forms 应用程序,包含一个主窗体(Form1)和一个子窗体(Form2)。

功能概述:

  • 在窗体加载时,创建一个 Form2 对象(子窗体)并显示出来。
  • 将子窗体的 MdiParent 属性设置为当前窗体(Form1),以使子窗体成为主窗体的子窗体。
  • 使用 LayoutMdi 方法将子窗体按水平方向平铺排列。

这段代码的功能是在主窗体加载时创建并显示一个子窗体,并将子窗体与主窗体进行关联,最后将子窗体按水平方向平铺排列显示。

1.首先插入新的子窗体form1,并设置IsMdiContainer = True 属性。

2.子窗体并设置他们的父窗体属性。

定义主文件form1.cs

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.Show();

            frm2.MdiParent = this;

            // 排列
            LayoutMdi(MdiLayout.TileHorizontal);
        }
    }
}

计算器案例

该代码是一个简单的计算器应用程序,包含一个窗体(Form1)和一些控件(textBox1、textBox2、comboBox1、button1、label1)。

功能概述:

  • 在窗体加载时,默认选择索引为0的项(加法)。
  • 当用户点击按钮(button1)时,从文本框(textBox1、textBox2)中获取两个整数,并从组合框(comboBox1)中获取选择的操作符。
  • 根据选择的操作符进行相应的计算,并将结果显示在标签(label1)中。
  • 如果用户输入的数字格式不正确,会显示相应的错误提示消息框。

这段代码的功能是实现一个简单的计算器,根据用户输入的两个数字和选择的操作符进行相应的数学运算,并将结果显示在界面上。同时还进行了一些输入验证和错误处理。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 练习25
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int n1 = Convert.ToInt32(textBox1.Text.Trim());
                int n2 = Convert.ToInt32(textBox2.Text.Trim());
                string oper = comboBox1.SelectedItem.ToString();
                switch (oper)
                {
                    case "+": label1.Text = (n1 + n2).ToString();
                        break;
                    case "-": label1.Text = (n1 - n2).ToString();
                        break;
                    case "*": label1.Text = (n1 * n2).ToString();
                        break;
                    case "/": label1.Text = (n1 / n2).ToString();
                        break;
                    default: MessageBox.Show("请选择正确的操作符");
                        break;
                }
            }
            catch
            {
                MessageBox.Show("请输入正确的数字");
            }
        }
    }
}

浏览器控件的使用

该代码是一个简单的浏览器控件应用程序,包含一个窗体(Form1)和一些控件(textBox1、button1、webBrowser1)。

功能概述:

  • 当用户点击按钮(button1)时,从文本框(textBox1)中获取用户输入的网址。
  • 创建一个Uri对象,将用户输入的网址加上"http://"前缀,作为Uri的值。
  • 将创建的Uri赋值给浏览器控件(webBrowser1)的Url属性。
  • 这样就会加载并显示用户输入的网址对应的页面。

这段代码的功能是实现一个简单的浏览器控件,用户可以在文本框中输入网址,点击按钮后,浏览器控件会加载并显示相应的网页内容。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _03_浏览器控件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text;
            Uri uri = new Uri("http://"+text);
            webBrowser1.Url = uri;
        }
    }
}

ComboBox 控件

该代码是一个简单的下拉框应用程序,包含一个窗体(Form1)和一些控件(comboBox2、button1、button2)。

功能概述:

  • 当用户点击按钮1(button1)时,通过代码向下拉框(comboBox2)添加数据。
  • 代码使用Items.Add()方法将三个字符串项("张三"、"李四"、"王五")添加到下拉框的选项列表中。
  • 当用户点击按钮2(button2)时,通过代码清空下拉框的选项列表。
  • 代码使用Items.Clear()方法从下拉框中移除所有的选项。

这段代码的功能是实现在下拉框中添加和清空选项的功能。用户可以点击按钮1来添加指定的选项,点击按钮2来清空下拉框中的所有选项。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            //通过代码给下拉框添加数据
            comboBox2.Items.Add("张三");
            comboBox2.Items.Add("李四");
            comboBox2.Items.Add("王五");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            comboBox2.Items.Clear();
        }
    }
}

ComboBox 日期时间控件

该代码是一个日期选择器应用程序,包含一个窗体(Form1)和一些控件(cboYear、cboMonth、cboDays)。

功能概述:

  • 在程序加载时,将当前年份及之前的年份添加到下拉框(cboYear)中。
  • 当用户选择年份(cboYear)发生改变时,根据所选年份加载月份(cboMonth)。
  • 当用户选择月份(cboMonth)发生改变时,根据所选年份和月份确定该月的天数,并加载天数(cboDays)。

具体实现:

  • 在程序加载时(Form1_Load),通过循环将当前年份及之前的年份(从1949年开始)添加到下拉框(cboYear)中。
  • 当用户选择年份(cboYear)发生改变时,先清空月份下拉框(cboMonth)的选项,然后通过循环将1到12月份添加到月份下拉框中。
  • 当用户选择月份(cboMonth)发生改变时,先清空天数下拉框(cboDays)的选项。根据所选年份和月份,确定该月的天数,并通过循环将1到该月天数的数字添加到天数下拉框中。

该代码实现了一个简单的日期选择器功能,允许用户选择年份、月份和日期,并根据所选的年份和月份动态调整日期的可选范围。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _05日期选择器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //程序加载的时候 将年份添加到下拉框中
            //获得当前的年份
            int year = DateTime.Now.Year;

            for (int i = year; i >= 1949; i--)
            {
                cboYear.Items.Add(i + "年");
            }
        }
        /// 当年份发生改变的时候 加载月份
        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {

            //添加之前应该清空之前的内容
            cboMonth.Items.Clear();
            for (int i = 1; i <= 12; i++)
            {
                cboMonth.Items.Add(i + "月");
            }
        }

        /// 当月份发生改变的时候 加载天
        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            cboDays.Items.Clear();
            int day = 0;//定义一个变量来存储天数

            //获得月份 7月 12
            string strMonth = cboMonth.SelectedItem.ToString().Split(new char[] { '月' }, StringSplitOptions.RemoveEmptyEntries)[0];
            string strYear = cboYear.SelectedItem.ToString().Split(new char[] { '年' }, StringSplitOptions.RemoveEmptyEntries)[0];
            // MessageBox.Show(cboMonth.SelectedItem.ToString());
            int year = Convert.ToInt32(strYear);
            int month = Convert.ToInt32(strMonth);
            switch (month)
            { 
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12: day = 31;
                    break;
                case 2:
                    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
                    {
                        day = 29;
                    }
                    else
                    {
                        day = 28;
                    }
                    break;
                default: day = 30;
                    break;
            }

            for (int i = 1; i <= day; i++)
            {
                cboDays.Items.Add(i + "日");
            }
        }
    }
}

ListBox 遍历与选中

该代码是一个包含列表框控件(listBox1)的应用程序,具有以下功能:

功能概述:

  • 在程序加载时,向列表框(listBox1)添加两个项(1和200000)。
  • 当用户点击按钮(button1)时,遍历选中的项,并显示选中项的值。

具体实现:

  • 在程序加载时(Form1_Load),通过调用listBox1.Items.Add()方法向列表框添加两个项(1和200000)。
  • 当用户点击按钮(button1)时,使用循环遍历列表框的所有项。对于每个项,使用listBox1.SelectedItems.Contains()方法检查是否为选中项。如果是选中项,则通过MessageBox.Show()方法显示该项的值。

该代码实现了一个简单的列表框控件的遍历选中项功能,允许用户选择列表框中的项,并在点击按钮后显示选中项的值。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _06ListBox控件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add(1);
            listBox1.Items.Add(200000);
        }

        // 遍历选中
        private void button1_Click(object sender, EventArgs e)
        {
            for(int x=0;x<listBox1.Items.Count;x++)
            {
                if (listBox1.SelectedItems.Contains(listBox1.Items[x]))
                {
                    MessageBox.Show(listBox1.Items[x].ToString());
                }
            }
        }
    }
}

实现图片预览

如下图所示,左面ListBox控件,右面是一个pictureBox控件。

该代码是一个包含列表框和图片框控件的应用程序,具有以下功能:

功能概述:

  • 在程序加载时,获取指定目录下的所有jpg图片文件,并将文件名添加到列表框(listBox1)中。
  • 当用户双击列表框中的项时,在图片框(pictureBox1)中显示相应的图片。

具体实现:

  • 在程序加载时(Form1_Load),使用Directory.GetFiles()方法获取指定目录下的所有jpg图片文件的全路径,并遍历路径数组。
  • 对于每个路径,使用Path.GetFileName()方法获取文件名,并将文件名添加到列表框(listBox1)中。
  • 同时,将图片的全路径添加到一个List泛型集合(list)中,以便后续根据列表框的选中项加载相应的图片。
  • 当用户双击列表框中的项时(listBox1_DoubleClick事件),根据选中项的索引从List集合中获取相应的图片路径,然后使用Image.FromFile()方法加载该图片,并在图片框(pictureBox1)中显示。

该代码实现了一个简单的点击列表框项来更换显示图片的功能。用户可以在列表框中选择不同的图片文件,然后双击进行预览显示。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace _07实现点击更换照片
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //用来存储图片文件的全路径
        List<string> list = new List<string>();

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] path = Directory.GetFiles(@"C:\", "*.jpg");
            for (int i = 0; i < path.Length; i++)
            {
                string fileName = Path.GetFileName(path[i]);
                listBox1.Items.Add(fileName);

                //将图片的全路径添加到List泛型集合中
                list.Add(path[i]);
                //listBox1.Items.Add(path[i]);
            }
        }

        /// 双击播放图片
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(list[listBox1.SelectedIndex]);
        }
    }
}

双击播放音乐

该代码是一个包含列表框和音乐播放功能的应用程序,具有以下功能:

功能概述:

  • 在程序加载时,获取指定目录下的所有wav音乐文件,并将文件名添加到列表框(listBox1)中。
  • 当用户双击列表框中的项时,播放相应的音乐文件。

具体实现:

  • 在程序加载时(Form1_Load事件),使用Directory.GetFiles()方法获取指定目录下的所有wav音乐文件的全路径,并遍历路径数组。
  • 对于每个路径,使用Path.GetFileName()方法获取文件名,并将文件名添加到列表框(listBox1)中。
  • 同时,将音乐文件的全路径添加到一个List泛型集合(listSongs)中,以便后续根据列表框的选中项播放相应的音乐文件。
  • 当用户双击列表框中的项时(listBox1_DoubleClick事件),根据选中项的索引从List集合中获取相应的音乐文件路径,然后创建一个SoundPlayer对象,并使用SoundPlayer.SoundLocation属性设置音乐文件的路径。
  • 最后,使用SoundPlayer.Play()方法播放音乐文件。

该代码实现了一个简单的双击列表框项来播放音乐的功能。用户可以在列表框中选择不同的音乐文件,然后双击进行播放。音乐文件使用SoundPlayer类来实现播放功能。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Media;

namespace _08双击播放音乐
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //存储音乐文件的全路径
        List<string> listSongs = new List<string>();
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] path = Directory.GetFiles(@"C:\Music", "*.wav");
            for (int i = 0; i < path.Length; i++)
            {
                string fileName = Path.GetFileName(path[i]);
                listBox1.Items.Add(fileName);
                //将音乐文件的全路径存到泛型集合中
                listSongs.Add(path[i]);
            }
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            SoundPlayer sp = new SoundPlayer();
            sp.SoundLocation=listSongs[listBox1.SelectedIndex];
            sp.Play();
        }
    }
}

打开文件对话框

该代码实现了一个打开对话框的功能,允许用户选择要打开的文件,并将文件内容显示在文本框中。

具体实现:

  • 点击按钮(button1_Click事件)时,创建一个OpenFileDialog对象(ofd)作为文件选择对话框。
  • 设置对话框的标题、是否允许多选、初始目录和文件类型过滤器等属性。
  • 调用对话框的ShowDialog()方法展示对话框,等待用户选择文件。
  • 获取用户选择的文件路径(ofd.FileName)并判断路径是否为空,如果为空则退出。
  • 使用FileStream打开选中文件(以读取模式),创建一个缓冲区(buffer)来存储读取到的数据。
  • 使用FileStream的Read()方法读取文件内容到缓冲区,返回实际读取的字节数。
  • 将缓冲区的数据使用Encoding.Default.GetString()方法转换为文本字符串,并显示在文本框(textBox1)中。

该代码实现了一个简单的打开对话框功能,用户可以通过对话框选择要打开的文件,并将文件的内容显示在文本框中。文件的读取使用了FileStream和字节数组的方式进行,然后将字节数组转换为字符串显示在文本框中。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace _10打开对话框
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //点击弹出对话框
            OpenFileDialog ofd = new OpenFileDialog();
            //设置对话框的标题
            ofd.Title = "请选择要打开的文本";
            //设置对话框可以多选
            ofd.Multiselect = true;
            //设置对话框的初始目录
            ofd.InitialDirectory = @"C:\";
            //设置对话框的文件类型
            ofd.Filter = "文本文件|*.txt|媒体文件|*.wmv|图片文件|*.jpg|所有文件|*.*";
            //展示对话框
            ofd.ShowDialog();

            //获得在打开对话框中选中文件的路径
            string path = ofd.FileName;
            if (path == "")
            {
                return;
            }
            using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                //实际读取到的字节数
                int r = fsRead.Read(buffer, 0, buffer.Length);

                textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
            }
        }
    }
}

保存文件对话框

该代码实现了一个保存文件对话框的功能,允许用户选择保存文件的路径并将文本框中的内容保存到文件中。

具体实现:

  • 点击按钮(button1_Click事件)时,创建一个SaveFileDialog对象(sfd)作为保存文件对话框。
  • 设置对话框的标题、初始目录和文件类型过滤器等属性。
  • 调用对话框的ShowDialog()方法展示对话框,等待用户选择保存文件的路径。
  • 获取用户选择的保存文件路径(sfd.FileName)并判断路径是否为空,如果为空则退出。
  • 使用FileStream打开或创建选中的文件(以写入模式),创建一个字节数组(buffer)并将文本框中的内容转换为字节数组。
  • 使用FileStream的Write()方法将字节数组写入文件中。
  • 提示保存成功。

该代码实现了一个简单的保存文件对话框功能,用户可以通过对话框选择保存文件的路径,然后将文本框中的内容保存到选中的文件中。文件的写入使用了FileStream和字节数组的方式进行,将文本内容转换为字节数组后写入文件中。保存成功后会显示保存成功的提示框。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _11_保存文件对话框
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "请选择要保存的路径";
            sfd.InitialDirectory = @"C:\";
            sfd.Filter = "文本文件|*.txt|所有文件|*.*";
            sfd.ShowDialog();
            //获得保存文件的路径
            string path = sfd.FileName;
            if (path == "")
            {
                return;
            }
            using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buffer = Encoding.Default.GetBytes(textBox1.Text);
                fsWrite.Write(buffer, 0, buffer.Length);
            }
            MessageBox.Show("保存成功");
        }
    }
}

字体颜色对话框

该代码实现了一个字体和颜色对话框的功能,允许用户选择字体和颜色,并将选择应用到文本框中。

具体实现:

  • 点击按钮1(button1_Click事件)时,创建一个FontDialog对象(fd)作为字体对话框。
  • 调用对话框的ShowDialog()方法展示字体对话框,等待用户选择字体。
  • 获取用户选择的字体(fd.Font)并将其应用到文本框的字体。
  • 点击按钮2(button2_Click事件)时,创建一个ColorDialog对象(cd)作为颜色对话框。
  • 调用对话框的ShowDialog()方法展示颜色对话框,等待用户选择颜色。
  • 获取用户选择的颜色(cd.Color)并将其应用到文本框的前景色(文字颜色)。

该代码实现了一个简单的字体和颜色对话框功能,用户可以通过字体对话框选择文本框的字体,通过颜色对话框选择文本框的前景色(文字颜色)。选择完成后,文本框的字体和前景色会相应地更新。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _12_字体和颜色对话框
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// 字体对话框
        private void button1_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            fd.ShowDialog();
            textBox1.Font = fd.Font;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ColorDialog cd = new ColorDialog();
            cd.ShowDialog();
            textBox1.ForeColor = cd.Color;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

panel 显示隐藏面板

该代码实现了一个简单的面板控件的显示和隐藏功能。

具体实现:

  • 在窗体上放置了两个按钮(button1和button2)和一个面板控件(panel1)。
  • 点击按钮1(button1_Click事件)时,将面板控件的Visible属性设置为true,使其可见。
  • 点击按钮2(button2_Click事件)时,将面板控件的Visible属性设置为false,使其隐藏。

通过点击按钮1和按钮2,可以控制面板控件的显示和隐藏。

这个功能通常用于创建交互式界面,根据用户的操作动态显示或隐藏某些元素。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

简易记事本

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _14_记事儿本应用程序
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //加载程序的时候 隐藏panel
            panel1.Visible = false;
            //取消文本框的自动换行功能
            textBox1.WordWrap = false;
        }

        /// 点击按钮的时候 隐藏panel
        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
        }

        private void 影藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        List<string> list = new List<string>();

        /// 打开对话框
        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择要打开的文本文件";
            ofd.InitialDirectory = @"C:\Users\SpringRain\Desktop";
            ofd.Multiselect = true;
            ofd.Filter = "文本文件|*.txt|所有文件|*.*";
            ofd.ShowDialog();

            //获得用户选中的文件的路径
            string path = ofd.FileName;
            //将文件的全路径存储到泛型集合中
            list.Add(path);
            //获得了用户打开文件的文件名
            string fileName = Path.GetFileName(path);
            //将文件名放到ListBox中
            listBox1.Items.Add(fileName);
            if (path == "")
            {
                return;
            }
            using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buffer, 0, buffer.Length);
                textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
            }
        }

        /// 保存对话框
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = @"C:\Users\SpringRain\Desktop";
            sfd.Title = "请选择要保存的文件路径";
            sfd.Filter = "文本文件|*.txt|所有文件|*.*";
            sfd.ShowDialog();

            //获得用户要保存的文件的路径
            string path = sfd.FileName;
            if (path == "")
            {
                return;
            }
            using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buffer = Encoding.Default.GetBytes(textBox1.Text);
                fsWrite.Write(buffer, 0, buffer.Length);
            }
            MessageBox.Show("保存成功");
        }

        private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (自动换行ToolStripMenuItem.Text == "☆自动换行")
            {
                textBox1.WordWrap = true;
                自动换行ToolStripMenuItem.Text = "★取消自动换行";
            }
            else if (自动换行ToolStripMenuItem.Text == "★取消自动换行")
            {
                textBox1.WordWrap = false;
                自动换行ToolStripMenuItem.Text = "☆自动换行";
            }
        }

        private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            FontDialog fd = new FontDialog();
            fd.ShowDialog();
            textBox1.Font = fd.Font;
        }

        private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorDialog cd = new ColorDialog();
            cd.ShowDialog();
            textBox1.ForeColor = cd.Color;
        }

        /// 双击打开对应的文件
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            //要获得双击的文件所对应的全路径
            string path = list[listBox1.SelectedIndex];
            using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buffer, 0, buffer.Length);

                textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
            }
        }
    }
}

音乐选择框

这段代码实现了一个简单的音乐播放器功能。

具体实现:

  • 在窗体上放置了几个按钮(button1、button2、button3)和一个ListBox控件(listBox1)。
  • 点击按钮1(button1_Click事件)时,弹出文件选择对话框(OpenFileDialog),让用户选择音乐文件。选择的文件名将显示在ListBox中,并将音乐文件的全路径存储在listSongs集合中。
  • 双击ListBox中的音乐文件(listBox1_DoubleClick事件),将选中的音乐文件路径设置给SoundPlayer对象(sp)的SoundLocation属性,并调用Play方法播放音乐。
  • 点击按钮2(button2_Click事件),实现上一曲功能。根据当前选中的音乐文件的索引,将索引减1,并播放上一首音乐。
  • 点击按钮3(button3_Click事件),实现下一曲功能。根据当前选中的音乐文件的索引,将索引加1,并播放下一首音乐。

通过这些功能,用户可以选择音乐文件并播放、切换上一曲和下一曲。注意,音乐文件的路径需要根据实际情况进行修改,以确保找到正确的音乐文件。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Media;
namespace _01复习
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //用来存储音乐文件的全路径
        List<string> listSongs = new List<string>();
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择音乐文件";
            ofd.InitialDirectory = @"C:\Users\SpringRain\Desktop\Music";
            ofd.Multiselect = true;
            ofd.Filter = "音乐文件|*.wav|所有文件|*.*";
            ofd.ShowDialog();
            //获得我们在文件夹中选择所有文件的全路径
            string[] path = ofd.FileNames;
            for (int i = 0; i < path.Length; i++)
            {
                //将音乐文件的文件名加载到ListBox中
                listBox1.Items.Add(Path.GetFileName(path[i]));
                //将音乐文件的全路径存储到泛型集合中
                listSongs.Add(path[i]);
            }
        }

        /// 实现双击播放
        SoundPlayer sp = new SoundPlayer();
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
           
            sp.SoundLocation=listSongs[listBox1.SelectedIndex];
            sp.Play();
        }

        /// 点击下一曲
        private void button3_Click(object sender, EventArgs e)
        {
            //获得当前选中歌曲的索引
            int index = listBox1.SelectedIndex;
            index++;
            if (index == listBox1.Items.Count)
            {
                index = 0;
            }
            //将改变后的索引重新的赋值给我当前选中项的索引
            listBox1.SelectedIndex = index;
            sp.SoundLocation = listSongs[index];
            sp.Play();
        }

        /// 点击上一曲
        private void button2_Click(object sender, EventArgs e)
        {
            int index = listBox1.SelectedIndex;
            index--;
            if (index < 0)
            {
                index = listBox1.Items.Count-1;
            }
            //将重新改变后的索引重新的赋值给当前选中项
            listBox1.SelectedIndex = index;
            sp.SoundLocation = listSongs[index];
            sp.Play();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

标签与随机数

这段代码实现了一个简单的摇奖机应用程序。

具体实现:

  • 在窗体上放置了一个标签(label1、label2、label3)和一个按钮(button1)。
  • 初始状态下,按钮文本显示为"开始",标志变量b为false。
  • 点击按钮1(button1_Click事件),根据当前按钮的状态执行不同操作:
    • 如果b为false,表示当前处于停止状态,点击按钮后需要开始摇奖。将b设置为true,按钮文本改为"停止"。 启动一个新线程(Thread)调用PlayGame方法进行摇奖。
    • 如果b为true,表示当前处于运行状态,点击按钮后需要停止摇奖。将b设置为false,按钮文本改为"开始"。
  • PlayGame方法是一个线程方法,用于进行摇奖操作。在循环中,通过Random类生成随机数,并将随机数显示在标签上。 当b为false时,结束循环,停止摇奖。

通过这个应用程序,用户可以点击按钮开始或停止摇奖,摇奖的结果将显示在标签上。需要注意的是,这里使用了多线程来实现摇奖过程,需要注意线程的安全性和控制线程的生命周期。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _05_摇奖机应用程序
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        bool b = false;
        private void button1_Click(object sender, EventArgs e)
        {
            if (b == false)
            {
                b = true;
                button1.Text = "停止";
                Thread th = new Thread(PlayGame);
                th.IsBackground = true;
                th.Name = "新线程";
               // th.
                th.Start();
            }
            else//b==true
            {
                b = false;
                button1.Text = "开始";
            }
            //PlayGame();
        }
        private void PlayGame()
        {
            Random r = new Random();
            while (b)
            {
                label1.Text = r.Next(0, 10).ToString();
                label2.Text = r.Next(0, 10).ToString();
                label3.Text = r.Next(0, 10).ToString();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}

网络编程中的应用

客户端设计

这段代码实现了一个简单的客户端应用程序,用于与服务器进行通信。

具体实现:

  • 在窗体上放置了文本框(txtServer、txtPort、txtMsg、txtLog)和按钮(btnStart、btnSend)以及一个文本框(txtLog)用于显示日志。
  • 点击btnStart按钮(btnStart_Click事件)开始与服务器建立连接。首先创建一个Socket对象,指定使用TCP协议进行通信。 通过解析输入的服务器地址(txtServer)和端口号(txtPort),创建一个IPEndPoint对象,用于连接服务器。 调用socket的Connect方法与服务器建立连接,并显示连接成功的消息。 然后创建一个新的线程(th),调用Rec方法进行接收服务器消息的操作。
  • Rec方法是一个循环,通过socket的Receive方法接收服务器发送的数据。根据接收到的数据的第一个字节进行判断:
    • 如果字节为0,表示接收到的是普通消息,将接收到的数据转换为字符串,并调用ShowMsg方法显示在日志文本框中。
    • 如果字节为1,表示接收到的是文件数据。弹出保存文件对话框(SaveFileDialog),让用户选择保存的路径。 将接收到的数据保存到用户指定的文件中,并显示保存成功的消息。
    • 如果字节不为0或1,则调用ZD方法进行闪烁窗口的操作。
  • ZD方法是用于窗口闪烁的方法。通过修改窗口的Location属性,使窗口位置在两个坐标之间循环移动,以实现闪烁效果。 在循环中,通过修改窗口的Location属性,使窗口位置在两个坐标之间来回移动。
  • ShowMsg方法用于将接收到的消息显示在日志文本框中,通过调用txtLog.AppendText方法追加文本到文本框中。
  • 点击btnSend按钮(btnSend_Click事件)向服务器发送消息。将文本框txtMsg中的内容转换为字节数组,并通过socket的Send方法发送给服务器。

通过这个客户端应用程序,用户可以与服务器建立连接,并进行消息的收发操作。接收到的消息可以显示在日志文本框中,用户也可以向服务器发送消息。需要注意的是,该应用程序中使用了多线程,需要注意线程的安全性和控制线程的生命周期。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socket;
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                socket.Connect(point);
                ShowMsg("连接成功");

                Thread th = new Thread(Rec);
                th.IsBackground = true;
                th.Start();
            }
            catch
            { }
        }


        void Rec()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    int r = socket.Receive(buffer);
                    if (buffer[0] == 0)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r-1);
                        ShowMsg(s);
                    }
                    else if (buffer[0] == 1)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter = "所有文件|*.*";
                        sfd.ShowDialog(this);
                        string path = sfd.FileName;
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        MessageBox.Show("保存成功");
                    }
                    else
                    {
                        ZD();
                    }
                }
                catch
                { 
                    
                }
            }
        }

        void ZD()
        {
            for (int i = 0; i < 500; i++)
            {
                this.Location = new Point(200, 200);
                this.Location = new Point(210, 210);
            }
        }


        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

        /// 给服务器发送消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
            socket.Send(buffer);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}

服务端设计

这段代码实现了一个简单的服务器应用程序,用于与客户端进行通信。

具体实现:

  • 在窗体上放置了文本框(txtPort、txtMsg、txtPath)和按钮(btnStart、btnSend、btnSelect、btnSendFile、btnZD)以及一个文本框(txtLog)用于显示日志,还有一个下拉框(cboUsers)用于显示连接的客户端IP地址。
  • 点击btnStart按钮(btnStart_Click事件)开始监听客户端连接。首先创建一个Socket对象,指定使用TCP协议进行通信。 通过解析输入的端口号(txtPort),创建一个IPEndPoint对象,用于绑定服务器的IP地址和端口号。 调用socketWatch的Bind方法将Socket与IPEndPoint进行绑定,然后显示监听成功的消息。 使用socketWatch的Listen方法开始监听客户端连接。 创建一个新的线程(th),调用Listen方法进行接收客户端连接的操作。
  • Listen方法是一个循环,通过socketWatch的Accept方法接收客户端的连接。将客户端的IP地址添加到下拉框(cboUsers)中, 并将IP地址和对应的客户端Socket存储在字典(dicSocket)中。 显示客户端连接成功的消息,并创建一个新的线程(th)用于接收客户端发送的消息。
  • Rec方法用于接收客户端发送的消息。通过Socket的Receive方法接收客户端发送的数据,并将接收到的数据转换为字符串, 然后调用ShowMsg方法显示在日志文本框中。
  • ShowMsg方法用于将接收到的消息显示在日志文本框中,通过调用txtLog.AppendText方法追加文本到文本框中。
  • 点击btnSend按钮(btnSend_Click事件)向客户端发送消息。将文本框txtMsg中的内容转换为字节数组,并通过字典(dicSocket) 根据选择的客户端IP地址获取对应的Socket对象,调用Socket的Send方法发送消息。
  • 点击btnSelect按钮(btnSelect_Click事件)选择要发送的文件。弹出文件选择对话框(OpenFileDialog),让用户选择要发送的文件。 将文件的路径保存在txtPath文本框中。
  • 点击btnSendFile按钮(btnSendFile_Click事件)向客户端发送文件。根据选择的文件路径(txtPath),使用FileStream读取文件的内容, 将文件数据添加到字节数组中,并在数组的开头添加一个字节表示该数据是文件数据。 根据选择的客户端IP地址获取对应的Socket对象,调用Socket的Send方法发送文件数据。
  • 点击btnZD按钮(btnZD_Click事件)向客户端发送震动指令。创建一个字节数组,将字节值设置为2,表示震动指令。 根据选择的客户端IP地址获取对应的Socket对象,调用Socket的Send方法发送震动指令。

通过这个服务器应用程序,用户可以启动服务器并监听客户端连接。连接成功后,可以接收客户端发送的消息,并向客户端发送消息和文件,还可以发送震动指令使客户端窗口闪烁。需要注意的是,该应用程序中使用了多线程,需要注意线程的安全性和控制线程的生命周期。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server

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

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ip = IPAddress.Any;//IPAddress.Parse(txtServer.Text);

                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                socketWatch.Bind(point);

                ShowMsg("监听成功");

                //去厕所蹲坑 
                socketWatch.Listen(10);

                //不停的接收客户端的连接
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch
            { }
        }

        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        void Listen(object o)
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                //循环的接收客户端的连接
                Socket socketSend = socketWatch.Accept();
                //将客户端的IP地址存储到下拉框中
                cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
                //将IP地址和这个客户端的Socket放到键值对集合中
                dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");

                //客户端连接成功后,就应高接收客户端发来的消息
                Thread th = new Thread(Rec);
                th.IsBackground = true;
                th.Start(socketSend);

            }
        }

        void Rec(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    int r = socketSend.Receive(buffer);

                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + str);
                }
                catch
                { }
            }
        }


        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// 服务器给客户端发送消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text);
            //获得客户端的ip
            string ip = cboUsers.SelectedItem.ToString();
            List<byte> list = new List<byte>();
            list.Add(0);
            list.AddRange(buffer);
            byte[] newBuffer = list.ToArray();

            dicSocket[ip].Send(newBuffer);
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "所有文件|*.*";
            ofd.ShowDialog();
            txtPath.Text = ofd.FileName;
        }

        private void btnSendFile_Click(object sender, EventArgs e)
        {
            string path = txtPath.Text;
            using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 3];
                int r = fsRead.Read(buffer, 0, buffer.Length);
                List<byte> list = new List<byte>();
                list.Add(1);
                list.AddRange(buffer);
                byte[] newBuffer = list.ToArray();
                string ip = cboUsers.SelectedItem.ToString();
                dicSocket[ip].Send(newBuffer, 0, r+1, SocketFlags.None);
            }
        }

        private void btnZD_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;
            string ip = cboUsers.SelectedItem.ToString();
            dicSocket[ip].Send(buffer);
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}

GDI 绘制登录验证码

需要一个pictureBox1控件,你可以自行拖拽上去。

这段代码实现了一个简单的验证码生成程序,使用GDI绘制验证码并在窗体上显示。

具体实现:

  • 在窗体上放置了一个PictureBox控件(pictureBox1)用于显示生成的验证码图片。
  • 当用户点击pictureBox1时,会触发pictureBox1_Click事件,生成新的验证码。
  • 在pictureBox1_Click事件处理程序中,首先创建一个Random对象r用于生成随机数。
  • 然后通过循环生成一个由5个随机数字组成的字符串。
  • 创建一个Bitmap对象bmp作为绘制验证码的画布,设置画布的尺寸为150x40像素。
  • 通过Graphics对象g从Bitmap对象bmp中创建绘图对象,用于在画布上绘制验证码。
  • 循环5次,分别在画布上绘制每个数字。使用随机选择的字体和颜色,绘制每个数字字符,位置依次偏移20个像素。
  • 随机绘制20条直线和500个黑色像素,增加验证码的复杂度和视觉效果。
  • 将绘制好的验证码图片bmp设置为pictureBox1的Image属性,显示在窗体上。

通过这个程序,用户可以点击验证码图片来获取新的验证码,每次生成的验证码都是随机的,并且具有一定的视觉干扰,提高验证码的安全性和可读性。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 使用GDI绘制验证码
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// 点击更换验证码
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            string str = null;
            for (int i = 0; i < 5; i++)
            {
                int rNumber = r.Next(0, 10);
                str += rNumber;
            }
            //  MessageBox.Show(str);
            //创建GDI对象
            Bitmap bmp = new Bitmap(150, 40);
            Graphics g = Graphics.FromImage(bmp);

            for (int i = 0; i < 5; i++)
            {
                Point p = new Point(i * 20, 0);
                string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
                Color[] colors = { Color.Yellow, Color.Blue, Color.Black, Color.Red, Color.Green };
                g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p);
            }

            for (int i = 0; i < 20; i++)
            {
                Point p1=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                Point p2=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                g.DrawLine(new Pen(Brushes.Green), p1, p2);
            }

            for (int i = 0; i < 500; i++)
            {
                Point p=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
                bmp.SetPixel(p.X, p.Y, Color.Black);
            }


            //将图片镶嵌到PictureBox中
            pictureBox1.Image = bmp;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

GDI 图形绘制

这段代码展示了如何使用GDI绘制简单的图形和文字。

具体实现:

  • 窗体加载时,不执行任何操作。
  • 当用户点击"绘制直线"按钮(button1_Click事件),会创建一个Graphics对象g,用于在窗体上进行绘制。
  • 创建一个画笔对象Pen,设置颜色为红色。
  • 创建两个点p1和p2,表示直线的起始点和终止点。
  • 使用Graphics对象g的DrawLine方法绘制直线,传入画笔对象和起始点终止点的坐标。
  • 在窗体的Paint事件(Form1_Paint事件)中,也执行了绘制直线的操作,不过每次重绘窗体时都会执行该事件,所以可以看到直线不断叠加。
  • 当用户点击"绘制矩形"按钮(button2_Click事件),会创建一个Graphics对象g,用于在窗体上进行绘制。
  • 创建一个画笔对象Pen,设置颜色为黄色。
  • 创建一个矩形区域rec,设置位置和尺寸。
  • 使用Graphics对象g的DrawRectangle方法绘制矩形,传入画笔对象和矩形区域。
  • 当用户点击"绘制扇形"按钮(button3_Click事件),会创建一个Graphics对象g,用于在窗体上进行绘制。
  • 创建一个画笔对象Pen,设置颜色为蓝色。
  • 创建一个矩形区域rec,设置位置和尺寸。
  • 使用Graphics对象g的DrawPie方法绘制扇形,传入画笔对象、矩形区域以及起始角度和扫描角度。
  • 当用户点击"绘制文字"按钮(button4_Click事件),会创建一个Graphics对象g,用于在窗体上进行绘制。
  • 使用Graphics对象g的DrawString方法绘制文字,传入文字内容、字体、画刷和位置。

通过这个程序,用户可以通过按钮点击来绘制不同的图形和文字,展示了GDI绘图的基本操作。每次点击按钮都会在窗体上绘制相应的图形或文字。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 使用GDI绘制简单的图形
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //一根笔 颜色  一张纸  两点 绘制直线的对象
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //创建GDI对象
            Graphics g = this.CreateGraphics();// new Graphics();
            //创建画笔对象
            Pen pen = new Pen(Brushes.Red);
            //创建两个点
            Point p1 = new Point(30, 50);
            Point p2 = new Point(250, 250);
            g.DrawLine(pen, p1, p2);

        }
        int i = 0;
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            i++;
            label1.Text = i.ToString();
            Graphics g = this.CreateGraphics();// new Graphics();
            //创建画笔对象
            Pen pen = new Pen(Brushes.Red);
            //创建两个点
            Point p1 = new Point(30, 50);
            Point p2 = new Point(250, 250);
            g.DrawLine(pen, p1, p2);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            Pen pen=new Pen(Brushes.Yellow);
            Size size=new System.Drawing.Size(80,80);
            Rectangle rec=new Rectangle(new Point(50,50),size);
            g.DrawRectangle(pen,rec);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            Pen pen=new Pen(Brushes.Blue);
            Size size=new System.Drawing.Size(180,180);
            Rectangle rec=new Rectangle(new Point(150,150),size);
            g.DrawPie(pen, rec, 60, 60);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            g.DrawString("百度网盘下载最快", new Font("宋体", 20, FontStyle.Underline), Brushes.Black, new Point(300, 300));
        }
    }
}
  • 3
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值