按鈕與編輯框的使用
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();