想在控制台做个类似WINFORM里的Closed事件来杀死线程。
解决方案 »
- 可不可以将.Netframework 4.0和开发的程序一起做一个安装程序,可以自动安装,不需要分开安装呢?
- C# 编译时 提示成员过期 怎么办
- 请教:如何在XML中存储<cq>这样的内容?
- 新建website怎么没有自动产生web.config文件?
- 我想用C#开发一个有手机短迅收发功能的软件,请问看什么书有帮助?
- 我要在WEB页面显示数据库里的一个表 而且是实事更新的 怎么做
- log4net多项目调用问题
- .Net中,reader[x].Value 方法是是如何实现的
- 对话框一闪而过
- 使用DATASET读取XML时,如何包含读取注释节点信息?等待大侠出手!
- 无法登陆到msn messenger,提示80048820,防火墙设置问题哦!所有挽救偏方都试了还是无效,似乎要永远告别msn了。
- 請高手解決一個低手問題,如何表示這個數組
foreach (System.Diagnostics.Process p in SysProcess)
{
p.Kill();
}
想在控制台做个类似WINFORM里的Closed事件来杀死线程。
Process[] SysProcess = Process.GetProcessesByName("进程名");
foreach (System.Diagnostics.Process p in SysProcess)
{
p.Kill();
}
这段你已经看清楚了,是“进程名”,不是线程,
结束线程就是Abort();如果你的线程是一个循环,可以控制该循环,比如
threadstatus=true;
while(threadstatus)
{
.............
}想结束的时候
threadstatus=false;
要杀线程的话同 wangsaokui(无间道III(MSMVP)) 。
{
try
{
//代码写在这里。
}
finally
{
//关闭事件。
}
}
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;namespace 测试控制台关闭信息
{
public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
//The SetConsoleCtrlHandler function adds or removes an application-defined HandlerRoutine function
//from the list of handler functions for the calling process.
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);
//一個Ctrl + C的信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent 函數
private const int CTRL_C_EVENT = 0;
//一個 Ctrl + Break 信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent 函數
private const int CTRL_BREAK_EVENT = 1;
//當用戶系統關閉Console時,系統會發送此信號到此
private const int CTRL_CLOSE_EVENT = 2;
//當用戶退出系統時系統會發送這個信號給所有的Console程序。該信號不能顯示是哪個用戶退出。
private const int CTRL_LOGOFF_EVENT = 5;
//當系統將要關閉時會發送此信號到所有Console程序
private const int CTRL_SHUTDOWN_EVENT = 6;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Class1 cl=new Class1();
}public Class1()
{
ConsoleCtrlDelegate newDategate=new ConsoleCtrlDelegate(HandlerRoutine);
bool re=SetConsoleCtrlHandler(newDategate,true);
if(re)
{
Console.WriteLine("Set SetConsoleCtrlHandler success!!");
}
else
{
Debug.WriteLine("Set SetConsoleCtrlHandler Error!!");
}
Console.ReadLine();
}bool HandlerRoutine(int CtrlType)
{
switch(CtrlType)
{
case CTRL_CLOSE_EVENT:
Console.Writeln("程序正在关闭..关闭线程");
//做关闭线程的操作
//需要注意的一点,在C#程序使用此API,系统只等待1秒的时间,如果你一秒内不执行完这些代码也没有办法
break;
}
return false;
}
}
}