要在程序关闭和电脑关闭时运行的代码

本文关键字:运行 代码 程序 电脑 | 更新日期: 2023-09-27 18:26:04

我有一个作为系统托盘应用程序运行的无表单应用程序。当计算机关闭或应用程序关闭时,我不得不运行代码。

这就是我目前拥有的

class sysTrayIcon
{
    public sysTrayIcon()
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(exitCode);
        SystemEvents.SessionEnding += new SessionEndingEventHandler(exitCode);
    }
    public void exitCode(object sender, EventArgs e)
    {            
        contactCman appClosing = new contactCman();
        bool didWeSuceed = appClosing.stampUserOut();            
        if (didWeSuceed == false)
        {
            MessageBox.Show("Stamp out function run returned fail!!");                
        }   
        else
        {
            MessageBox.Show("Stamp out function run returned success");
        }
    }
}
class contactCman
{
    public Dictionary<string, string> getUrlResponse(string toDo)
    {
        var url = mainSiteUrl + "/" + apiFileName + "?" + "userid=" + userid + "&pw=" + pw + "&toDo=" + toDo;
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        WebHeaderCollection header = response.Headers;
        var encoding = ASCIIEncoding.ASCII;
        string responseText;
        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
        {
            responseText = reader.ReadToEnd();
        }
        // key1=value1;key2=value2;key3=value3;
        var responseData = responseText.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
       .Select(part => part.Split('='))
       .ToDictionary(split => split[0], split => split[1]);
        return responseData;
    }    
    public Dictionary<string, string> checkLastStamp()
    {
        string toDo = "getLastStamp";
        Dictionary<string, string> urlResponse = getUrlResponse(toDo);
        return urlResponse;
    }
    public bool stampUserOut()
    {
        Dictionary<string, string> usersLastStamp = checkLastStamp();
        string valueOfKey;
        if (usersLastStamp.TryGetValue("checkInOut", out valueOfKey) && (valueOfKey == "in"))
        {
            string toDo = "stampUserOut";
            Dictionary<string, string> urlResponse = getUrlResponse(toDo);
            if (urlResponse.TryGetValue("Message", out valueOfKey) && (valueOfKey == "Success!"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }            
    }
}

我的问题是,当在visualstudio中通过调试器运行时,上面的代码可以正常工作(只在程序关闭的情况下进行测试)。如果我在外面运行,消息框永远不会出现。

要在程序关闭和电脑关闭时运行的代码

我认为最好听ApplicationExit事件。它将阻止应用程序实际退出,直到处理程序被执行:

static void Main()
{
    Application.ApplicationExit += Application_ApplicationExit;
    ...
}
static void Application_ApplicationExit(object sender, EventArgs e)
{
    MessageBox.Show("Exit!");
}
  1. 如果没有窗口,SessionEnding不会启动。看见http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending%28v=vs.110%29.aspx
  2. ProcessExit只有2秒钟的运行时间。现在显示消息框或执行任何交互式操作都为时已晚:http://msdn.microsoft.com/en-us/library/system.appdomain.processexit%28v=vs.110%29.aspx

我认为你要么需要一个服务,让它在登录/注销后保持活力,要么你需要创建一个窗口,让你有一个消息泵。