• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# WinForm 界面控件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

按钮与编辑框的使用

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

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)
        {
            // tianjia shuju
            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 窗体设计:

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

2.zi chuang ti bing she zhi ta men de fu chuang ti

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;

            // pai lie
            LayoutMdi(MdiLayout.TileHorizontal);
        }
    }
}

ji suan qi

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("请输入正确的数字");
            }
        }
    }
}

浏览器控件的使用

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 控件

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 日期时间控件

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 遍历与选中

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控件。

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]);
        }
    }
}

双击播放音乐:

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();
        }
    }
}

打开一个txt文件(打开文件对话框): 一个放大了的textbox

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);
            }
        }
    }
}

保存文件对话框:

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("保存成功");
        }
    }
}

字体颜色对话框

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 显示隐藏面板

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);
            }
        }
    }
}

音乐选择框

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)
        {

        }
    }
}

标签与随机数:

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;
        }
    }
}

Socket - client

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;
        }
    }
}

socket-server

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控件

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 图形绘制:

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));
        }
    }
}

窗体传值:
form1.cs 只有一个 label1 和一个button

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 窗体传值
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        void ShowMsg(string s)
        {
            label1.Text = s; 
        }
    }
}

form2.cs 一个textbox1 和一个button

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 窗体传值
{
    public delegate void DelStr(string s);
    public partial class Form2 : Form
    {
        public DelStr _del;

        // 子窗口中的del赋值给this._del 父窗体,完成的窗体进程数据传输。
        public Form2(DelStr del)
        {
            this._del = del;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 给父窗体赋值
            _del(textBox1.Text);
        }
    }
}

创建xml

	using System.Xml;
			
通过代码来创建XML文档
XmlDocument doc = new XmlDocument();

创建第一个行描述信息,并且添加到doc文档中
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);

创建根节点
XmlElement books = doc.CreateElement("Books");

将根节点添加到文档中
doc.AppendChild(books);

给根节点Books创建子节点
XmlElement book1 = doc.CreateElement("Book");

将book添加到根节点
books.AppendChild(book1);

给Book1添加子节点
XmlElement name1 = doc.CreateElement("Name");
name1.InnerText = "你好";
book1.AppendChild(name1);

写入一个XML

1、创建一个XML文档对象
XmlDocument doc = new XmlDocument();

2、创建第一行描述信息
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

3、将创建的第一行数据添加到文档中
doc.AppendChild(dec);

4、给文档添加根节点
XmlElement books = doc.CreateElement("Books");

5、将根节点添加给文档对象
doc.AppendChild(books);

6、给根节点添加子节点
XmlElement book1 = doc.CreateElement("Book");
将子节点book1添加到根节点下
books.AppendChild(book1);

7、给book1添加子节点
XmlElement bookName1 = doc.CreateElement("BookName");

8、设置标签中显示的文本
bookName1.InnerText = "水浒传";
book1.AppendChild(bookName1);

XmlElement author1 = doc.CreateElement("Author");
author1.InnerText = "<authorName>匿名</authorName>";
book1.AppendChild(author1);

XmlElement price1 = doc.CreateElement("Price");
price1.InnerXml = "<authorName>匿名</authorName>";
book1.AppendChild(price1);

XmlElement des1 = doc.CreateElement("Des");
des1.InnerXml = "好看";
book1.AppendChild(des1);

Console.WriteLine("保存成功");
doc.Save("Book.xml");
Console.ReadKey();

追加xml

追加XML文档
XmlDocument doc = new XmlDocument();
XmlElement books;
if (File.Exists("Books.xml"))
{
	如果文件存在 加载XML
	doc.Load("Books.xml");
	获得文件的根节点
	books = doc.DocumentElement;
}
else
{
	如果文件不存在
	创建第一行
	XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
	doc.AppendChild(dec);
	创建跟节点
	books = doc.CreateElement("Books");
	doc.AppendChild(books);
}

5、给根节点Books创建子节点
XmlElement book1 = doc.CreateElement("Book");
将book添加到根节点
books.AppendChild(book1);

6、给Book1添加子节点
XmlElement name1 = doc.CreateElement("Name");
name1.InnerText = "c#开发大全";
book1.AppendChild(name1);

XmlElement price1 = doc.CreateElement("Price");
price1.InnerText = "110";
book1.AppendChild(price1);

XmlElement des1 = doc.CreateElement("Des");
des1.InnerText = "看不懂";
book1.AppendChild(des1);

doc.Save("Books.xml");
Console.WriteLine("保存成功");
Console.ReadKey();

读取XML

加载要读取的XML
XmlDocument doc = new XmlDocument();
doc.Load("Books.xml");

获得根节点
XmlElement books = doc.DocumentElement;

获得子节点 返回节点的集合
XmlNodeList xnl = books.ChildNodes;
foreach (XmlNode item in xnl)
{
    Console.WriteLine(item.InnerText);
}
Console.ReadKey();

读取带属性的XML文档
XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");
Xpath

XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");
XmlNodeList xnl = doc.SelectNodes("/Order/Items/OrderItem");

foreach (XmlNode node in xnl)
{
    Console.WriteLine(node.Attributes["Name"].Value);
    Console.WriteLine(node.Attributes["Count"].Value);
}
Console.ReadKey();

改变属性的值
XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");
XmlNode xn = doc.SelectSingleNode("/Order/Items/OrderItem[@Name=\'190\']");
xn.Attributes["Count"].Value = "200";
xn.Attributes["Name"].Value = "颜世伟";
doc.Save("Order.xml");
Console.WriteLine("保存成功");
XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");
XmlNode xn = doc.SelectSingleNode("/Order/Items");

xn.RemoveAll();
doc.Save("Order.xml");
Console.WriteLine("删除成功");
Console.ReadKey();

获得文档的根节点
  xmlelement order = doc.documentelement;
  xmlnodelist xnl = order.childnodes;
  foreach (xmlnode item in xnl)
  {
      如果不是items 就continue
      if (item[])
      {
          continue;
      }
      console.writeline(item.attributes["name"].value);
      console.writeline(item.attributes["count"].value);
  }
Console.ReadKey();

增删改查:

XMLDocument
#region 对xml文档实现追加的需求
XmlDocument doc = new XmlDocument();
首先判断xml文档是否存在 如果存在 则追加  否则创建一个
if (File.Exists("Student.xml"))
{
    加载进来
    doc.Load("Student.xml");
    追加
    获得根节点 给根节点添加子节点
    XmlElement person = doc.DocumentElement;

    XmlElement student = doc.CreateElement("Student");
    student.SetAttribute("studentID", "10");
    person.AppendChild(student);

    XmlElement name = doc.CreateElement("Name");
    name.InnerXml = "我是新来哒";
    student.AppendChild(name);

    XmlElement age = doc.CreateElement("Age");
    age.InnerXml = "18";
    student.AppendChild(age);

    XmlElement gender = doc.CreateElement("Gender");
    gender.InnerXml = "女";
    student.AppendChild(gender);

}
else
{
    不存在

    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
    doc.AppendChild(dec);

    XmlElement person = doc.CreateElement("Person");
    doc.AppendChild(person);


    XmlElement student = doc.CreateElement("Student");
    student.SetAttribute("studentID", "110");
    person.AppendChild(student);

    XmlElement name = doc.CreateElement("Name");
    name.InnerXml = "张三三李思思";
    student.AppendChild(name);

    XmlElement age = doc.CreateElement("Age");
    age.InnerXml = "28";
    student.AppendChild(age);

    XmlElement gender = doc.CreateElement("Gender");
    gender.InnerXml = "男";
    student.AppendChild(gender);
}

doc.Save("Student.xml");
Console.WriteLine("保存成功"); 
#endregion


#region 读取XML文档
XmlDocument doc = new XmlDocument();

doc.Load("OrDER.xml");

还是 先获得根节点
XmlElement order = doc.DocumentElement;
获得根节点下面的所有子节点
XmlNodeList xnl = order.ChildNodes;

foreach (XmlNode item in xnl)
{
    Console.WriteLine(item.InnerText);
}
XmlElement items = order["Items"];
XmlNodeList xnl2 = items.ChildNodes;
foreach (XmlNode item in xnl2)
{
    Console.WriteLine(item.Attributes["Name"].Value);
    Console.WriteLine(item.Attributes["Count"].Value);

    if (item.Attributes["Name"].Value == "手套")
    {
        item.Attributes["Count"].Value = "新来哒";
    }
}

doc.Save("OrDER.xml"); 
#endregion



#region 使用XPath的方式来读取XML文件


XmlDocument doc = new XmlDocument();
doc.Load("order.xml");
获得根节点
XmlElement order = doc.DocumentElement;
XmlNode xn = order.SelectSingleNode("/Order/Items/OrderItem[@Name=\'雨衣\']");

Console.WriteLine(xn.Attributes["Name"].Value);

xn.Attributes["Count"].Value = "woshi new";


doc.Save("order.xml");
Console.WriteLine("保存成功");
#endregion



XmlDocument doc = new XmlDocument();

doc.Load("order.xml");


doc.RemoveAll();不行 根节点不允许删除

XmlElement order = doc.DocumentElement;

order.RemoveAll();移除根节点下的所有子节点

 XmlNode xn = order.SelectSingleNode("/Order/Items/OrderItem[@Name=\'雨衣\']");


 让orderItem去删除属性
 XmlNode orderItem = order.SelectSingleNode("/Order/Items/OrderItem");

 获得Items节点

 XmlNode items = order["Items"];order.SelectSingleNode("/Order/Items");


 items.RemoveChild(xn);移除当前节点

 orderItem.RemoveAttributeNode(xn.Attributes["Count"]);

 xn.Attributes.RemoveNamedItem("Count");

 doc.Save("order.xml");
 Console.WriteLine("删除成功");
 Console.ReadKey();

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
使用C#和Excel进行报表开发(八)-用程序绑定数据源发布时间:2022-07-10
下一篇:
C#图像检测开源项目发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap