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