c# 代码整理集1

1 测量字体宽度
         private   void  button1_Click( object  sender, EventArgs e)
        
{
            Graphics g 
= this.CreateGraphics();

            
string txt1, txt2;
            
float f1, f2;

            txt1 
= this.textBox1.Text.Trim();
            txt2 
= this.textBox2.Text.Trim();

            f1
=g.MeasureString(txt1,new Font("宋体",9f)).Width;
            f2
=g.MeasureString(txt2,new Font("宋体",9f)).Width;

            
this.textBox3.Text = f1.ToString().Trim();
            
this.textBox4.Text = f2.ToString().Trim();

        }
 
2 tcp 通讯

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

namespace  tcp
{
    
public partial class Form1 : Form
    
{
        
/// <summary>
        
/// 创建线程,用以侦听端口号,接收信息 
        
/// </summary>

        private Thread th;
        
/// <summary>
        
/// //用以侦听端口号 
        
/// </summary>

        private TcpListener tlListen1;
        
/// <summary>
        
/// //设定标示位,判断侦听状态 
        
/// </summary>

        private bool listenerRun = true;
        
        
/// <summary>
        
/// //创建传送/接收的基本数据流实例 
        
/// </summary>

        private NetworkStream tcpStream;
        
/// <summary>
        
/// //用以实现向远程主机传送信息 
        
/// </summary>

        private StreamWriter reqStreamW;
        
/// <summary>
        
/// //用以创建对远程主机的连接 
        
/// </summary>

        private TcpClient tcpc;
        
        
private Socket skSocket;
        
//用以接收远程主机传送来的数据 



        
public Form1()
        
{
            InitializeComponent();
        }




        
private void talk()
        
{
            
try
            
{
                System.Net.Sockets.TcpListener tlListen1 
= new TcpListener(5088);
                
                
//侦听端口号 
                tlListen1.Start();
                Socket skSocket 
= tlListen1.AcceptSocket();

                
//接受远程计算机的连接请求,并获得用以接收数据的Socket实例 
                EndPoint tempRemoteEP = skSocket.RemoteEndPoint;
                
//获得远程计算机对应的网络远程终结点 
                while (true)
                
{
                    Byte[] byStream 
= new Byte[80];
                    
//定义从远程计算机接收到数据存放的数据缓冲区 
                    int i = skSocket.ReceiveFrom(byStream, ref tempRemoteEP);
                    
//接收数据,并存放到定义的缓冲区中 
                    string sMessage = System.Text.Encoding.UTF8.GetString(byStream);
                    
//以指定的编码,从缓冲区中解析出内容 
                    MessageBox.Show(sMessage);
                    
//显示传送来的数据 
                }

            }

            
catch (System.Security.SecurityException)
            
{
                MessageBox.Show(
"防火墙安全错误!""错误",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
 
        }


        
void Form1_Load(object sender, System.EventArgs e)
        
{
            
//throw new System.Exception("The method or operation is not implemented.");
        }


        
void button4_Click(object sender, System.EventArgs e)
        
{
            
try
            
{
                
string sMsg = textBox4.Text;
                
string MyName = Dns.GetHostName();
                
//以特定的编码往向数据流中写入数据, 
                
//默认为UTF8Encoding 的实例 
                reqStreamW = new StreamWriter(tcpStream);
                
//将字符串写入数据流中 
                reqStreamW.Write(sMsg);
                
//清理当前编写器的所有缓冲区,并使所有缓冲数据写入基础流 
                reqStreamW.Flush();
                
string time = DateTime.Now.ToString();
                
//显示传送的数据和时间 
                listBox1.Items.Add(time + " " + MyName + ":");
                listBox1.Items.Add(sMsg);
                textBox4.Clear();
            }

            
//异常处理 
            catch (Exception)
            
{
                statusBar1.Panels[
0].Text = "无法发送信息到目标计算机!";
            }
 

        }


        
void button3_Click(object sender, System.EventArgs e)
        
{
            th 
= new Thread(new ThreadStart(Listen));
            
//以Listen过程来初始化线程实例 
            th.Start();
            
//启动此线程 

        }


        
void button2_Click(object sender, System.EventArgs e)
        
{
            listenerRun 
= false;
            tcpc.Close();
            statusBar1.Panels[
0].Text = "断开连接!";
            button1.Enabled 
= true;
            button2.Enabled 
= false;
            button4.Enabled 
= false

        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            
try
            
{
                tcpc 
= new TcpClient(textBox1.Text,Int32.Parse(textBox3.Text));
                
//向远程计算机提出连接申请 
                tcpStream = tcpc.GetStream();
                
//如果连接申请建立,则获得用以传送数据的数据流 
                statusBar1.Panels[0].Text = "成功连接远程计算机!";
                button2.Enabled 
= true;
                button1.Enabled 
= false;
                button4.Enabled 
= true;
            }

            
catch (Exception)
            
{
                statusBar1.Panels[
0].Text = "目标计算机拒绝连接请求!";
            }

        }


        
private void Listen()
        
{
            
try
            
{
                
//statusBar1.Panels[1].Text = "正在监听...";

                
//侦听指定端口号 
                tlListen1 = new TcpListener(Int32.Parse(textBox2.Text));
                tlListen1.Start();
                
                
//接受远程计算机的连接请求,并获得用以接收数据的Socket实例 
                skSocket = tlListen1.AcceptSocket();

                
//获得远程计算机对应的网络远程终结点 
                EndPoint tempRemoteEP = skSocket.RemoteEndPoint;

                IPEndPoint tempRemoteIP 
= (IPEndPoint)tempRemoteEP;

                IPHostEntry host 
= Dns.GetHostByAddress(tempRemoteIP.Address);

                
string HostName = host.HostName;
                
                
                
//根据获得的远程计算机对应的网络远程终结点获得远程计算机的名称 
                
//statusBar1.Panels[1].Text = "'" + HostName + "' " + "远程计算机正确连接!";
                
//循环侦听 
                while (listenerRun)
                
{
                    Byte[] stream 
= new Byte[80];
                    
//定义从远程计算机接收到数据存放的数据缓冲区 
                    
//获得当前的时间 
                    string time = DateTime.Now.ToString();
                    
                    
int i = skSocket.ReceiveFrom(stream,ref tempRemoteEP);
                    
//接收数据,并存放到定义的缓冲区中 
                    string sMessage = System.Text.Encoding.UTF8.GetString(stream);

                    
//以指定的编码,从缓冲区中解析出内容 
                    
//listBox2.Items.Add(time + "" + HostName + ":");
                    
//listBox2.Items.Add(sMessage);
                    
//显示接收到的数据 
                }

            }

            
catch (System.Security.SecurityException)
            
{
                MessageBox.Show(
"防火墙安全错误!""错误",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
 

    }

}

3 播放sound
using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Diagnostics;
using  System.Drawing;
using  System.Media;
using  System.Windows.Forms;

namespace  SoundApiExample
{
    
public class SoundTestForm : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.Label label1;
        
private System.Windows.Forms.TextBox filepathTextbox;
        
private System.Windows.Forms.Button playOnceSyncButton;
        
private System.Windows.Forms.Button playOnceAsyncButton;
        
private System.Windows.Forms.Button playLoopAsyncButton;
        
private System.Windows.Forms.Button selectFileButton;

        
private System.Windows.Forms.Button stopButton;
        
private System.Windows.Forms.StatusBar statusBar;
        
private System.Windows.Forms.Button loadSyncButton;
        
private System.Windows.Forms.Button loadAsyncButton;
        
private SoundPlayer player;

        
public SoundTestForm()
        
{
            
// Initialize Forms Designer generated code.
            InitializeComponent();

            
// Disable playback controls until a valid .wav file 
            
// is selected.
            EnablePlaybackControls(false);

            
// Set up the status bar and other controls.
            InitializeControls();

            
// Set up the SoundPlayer object.
            InitializeSound();
        }


        
// Sets up the status bar and other controls.
        private void InitializeControls()
        
{
            
// Set up the status bar.
            StatusBarPanel panel = new StatusBarPanel();
            panel.BorderStyle 
= StatusBarPanelBorderStyle.Sunken;
            panel.Text 
= "Ready.";
            panel.AutoSize 
= StatusBarPanelAutoSize.Spring;
            
this.statusBar.ShowPanels = true;
            
this.statusBar.Panels.Add(panel);
        }


        
// Sets up the SoundPlayer object.
        private void InitializeSound()
        
{
            
// Create an instance of the SoundPlayer class.
            player = new SoundPlayer();

            
// Listen for the LoadCompleted event.
            player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted);

            
// Listen for the SoundLocationChanged event.
            player.SoundLocationChanged += new EventHandler(player_LocationChanged);
        }


        
private void selectFileButton_Click(object sender,
            System.EventArgs e)
        
{
            
// Create a new OpenFileDialog.
            OpenFileDialog dlg = new OpenFileDialog();

            
// Make sure the dialog checks for existence of the 
            
// selected file.
            dlg.CheckFileExists = true;

            
// Allow selection of .wav files only.
            dlg.Filter = "WAV files (*.wav)|*.wav";
            dlg.DefaultExt 
= ".wav";

            
// Activate the file selection dialog.
            if (dlg.ShowDialog() == DialogResult.OK)
            
{
                
// Get the selected file's path from the dialog.
                this.filepathTextbox.Text = dlg.FileName;

                
// Assign the selected file's path to 
                
// the SoundPlayer object.  
                player.SoundLocation = filepathTextbox.Text;
            }

        }


        
// Convenience method for setting message text in 
        
// the status bar.
        private void ReportStatus(string statusMessage)
        
{
            
// If the caller passed in a message...
            if ((statusMessage != null&& (statusMessage != String.Empty))
            
{
                
// ...post the caller's message to the status bar.
                this.statusBar.Panels[0].Text = statusMessage;
            }

        }


        
// Enables and disables play controls.
        private void EnablePlaybackControls(bool enabled)
        
{
            
this.playOnceSyncButton.Enabled = enabled;
            
this.playOnceAsyncButton.Enabled = enabled;
            
this.playLoopAsyncButton.Enabled = enabled;
            
this.stopButton.Enabled = enabled;
        }


        
private void filepathTextbox_TextChanged(object sender,
            EventArgs e)
        
{
            
// Disable playback controls until the new .wav is loaded.
            EnablePlaybackControls(false);
        }


        
private void loadSyncButton_Click(object sender,
            System.EventArgs e)
        
{
            
// Disable playback controls until the .wav is 
            
// successfully loaded. The LoadCompleted event 
            
// handler will enable them.
            EnablePlaybackControls(false);

            
try
            
{
                
// Assign the selected file's path to 
                
// the SoundPlayer object.  
                player.SoundLocation = filepathTextbox.Text;

                
// Load the .wav file.
                player.Load();
            }

            
catch (Exception ex)
            
{
                ReportStatus(ex.Message);
            }

        }


        
private void loadAsyncButton_Click(System.Object sender,
            System.EventArgs e)
        
{
            
// Disable playback controls until the .wav is 
            
// successfully loaded. The LoadCompleted event 
            
// handler will enable them.
            EnablePlaybackControls(false);

            
try
            
{
                
// Assign the selected file's path to 
                
// the SoundPlayer object.  
                player.SoundLocation = this.filepathTextbox.Text;

                
// Load the .wav file.
                player.LoadAsync();
            }

            
catch (Exception ex)
            
{
                ReportStatus(ex.Message);
            }

        }


        
// Synchronously plays the selected .wav file once.
        
// If the file is large, UI response will be visibly 
        
// affected.
        private void playOnceSyncButton_Click(object sender,
            System.EventArgs e)
        
{
            ReportStatus(
"Playing .wav file synchronously.");
            player.PlaySync();
            ReportStatus(
"Finished playing .wav file synchronously.");
        }


        
// Asynchronously plays the selected .wav file once.
        private void playOnceAsyncButton_Click(object sender,
            System.EventArgs e)
        
{
            ReportStatus(
"Playing .wav file asynchronously.");
            player.Play();
        }


        
// Asynchronously plays the selected .wav file until the user
        
// clicks the Stop button.
        private void playLoopAsyncButton_Click(object sender,
            System.EventArgs e)
        
{
            ReportStatus(
"Looping .wav file asynchronously.");
            player.PlayLooping();
        }


        
// Stops the currently playing .wav file, if any.
        private void stopButton_Click(System.Object sender,
            System.EventArgs e)
        
{
            player.Stop();
            ReportStatus(
"Stopped by user.");
        }


        
// Handler for the LoadCompleted event.
        private void player_LoadCompleted(object sender,
            AsyncCompletedEventArgs e)
        
{
            
string message = String.Format("LoadCompleted: {0}",
                
this.filepathTextbox.Text);
            ReportStatus(message);
            EnablePlaybackControls(
true);
        }


        
// Handler for the SoundLocationChanged event.
        private void player_LocationChanged(object sender, EventArgs e)
        
{
            
string message = String.Format("SoundLocationChanged: {0}",
                player.SoundLocation);
            ReportStatus(message);
        }


        
Windows Form Designer generated code

        [STAThread]
        
static void Main()
        
{
            Application.Run(
new SoundTestForm());
        }

    }

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值