首先在Program.cs里面的 static void Main中添加
Process current = Process.GetCurrentProcess();
current.CloseMainWindow();
这是为了结束前询问是否真的退出
然后在在设计界面添加listbox,label,button(2个),效果如下
本地线程的基础知识
listBox1.Items.Clear();
Process[] allprocesses = Process.GetProcesses();
foreach (Process myprocess in allprocesses)
{
listBox1.Items.Add(“进程” + myprocess.ProcessName + “的ID为:” + Convert.ToString(myprocess.Id));// 将一个基本数据类型转换为另一个基本数据类型。
}
这段代码是查询本地进程以及相应的ID号
之后学习线程安全
private Thread safeThread;
delegate void SetTextCallback(String test); //委托机制实现安全访问线程
也就是使用委托
完整源码如下(Form.cs的):
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace 线程章节知识点总结
{
public partial class Form1 : Form
{
private Thread safeThread;
delegate void SetTextCallback(String test); //委托机制实现安全访问线程
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
Process[] allprocesses = Process.GetProcesses();
foreach (Process myprocess in allprocesses)
{
listBox1.Items.Add("进程" + myprocess.ProcessName + "的ID为:" + Convert.ToString(myprocess.Id));// 将一个基本数据类型转换为另一个基本数据类型。
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.label1.Text = ""
;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("您真的不用此软件了吗", "原创", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void 结束进程ToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.safeThread = new Thread(Funcsafe);
this.safeThread.Start();
}
private void Funcsafe()
{
this.SetText(DateTime.Now.ToString());
}
private void SetText(String text)
{
if (this.label1.InvokeRequired) //返回值为true证明是跨线程访问
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.label1.Text = text;
}
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}