好吧,这就是交易。我正在尝试制作一个 GUI 应用程序但没有 GUI 的应用程序。所以当应用程序启动时,它有一个带有登录屏幕的小表单(我已经完成了这部分)。
这是表单运行的代码,main()
但一旦关闭,我就将其处理掉。
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Create an instance of form1
Form1 form1 = new Form1();
Application.Run(form1);
if(form1.isLoggedIn)
{
filename = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username);
Flow palm = new Flow(new FlowArguments(form1.username, filename));
MessageBox.Show("Thankyou, exiting...");
form1.Dispose();
}
}
因此,正如您在表单关闭后所看到的那样,如果有人登录,则 main 会继续运行。如果您仔细观察,就会Flow
发现创建的类有一个实例。
这是一个非常短的课程,我们开始:
public class Flow
{
//global variables
FlowArguments FlowArgs;
System.Threading.Timer tm;
//constructor
public Flow(FlowArguments fmg)
{
FlowArgs = fmg;
tm = new System.Threading.Timer(Tick, null,
System.Threading.Timeout.Infinite, 10000);
using(StreamWriter sw = new StreamWriter(FlowArgs.Filename))
{
//sw.writelines that SO doesnt really care for.
}
//enable the timer
tm.Change(0, 100);
}
public void Tick(object State)
{
Console.WriteLine("Hello");
//a bunch of SteamWriter writeline methods that SO doesnt care for.
}
public void WriteProcesses(StreamWriter sw, DateTime dw)
{
var localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
foreach(Process p in localAll)
{
sw.WriteLine("@" + p.ProcessName +
"[" + dw.ToString("ddMMyyhhmm") + "]" +
"[" + FlowArgs.Username + "]");
}
}
}
如您所见,我确实启动了计时器。但是由于它使用System.Threading.Timer
(因为我在某处读到它Form.Timer
确实不合适)它在线程池上运行(根据 MSDN),但是当这种情况发生时,主窗体现在已经退出,Main()
因此程序关闭。
我可能的解决方案是什么?该计时器将每 10 分钟运行一次(抓取进程)。关闭 GUI 后,我计划制作一个系统图标托盘,用户可以使用它来关闭程序。