简体   繁体   English

代码在程序关闭和pc关闭时运行

[英]Code to be run on program close and pc shutdown

I have a formless application that runs as a system tray application. 我有一个无形的应用程序作为系统托盘应用程序运行。 Im struggling with it having to run code when the computer closes or when the application is closed. 我正在努力解决它在计算机关闭或应用程序关闭时运行代码的问题。

This is what i have so far 这就是我到目前为止所拥有的

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;
        }            
    }
}

My problem is that the code above works (only tested with the program close though) as intended when run through the debugger inside visual studio. 我的问题是,当通过Visual Studio内部的调试器运行时,上面的代码可以正常工作(只测试程序关闭)。 If i run it outside, the messagebox never appears. 如果我在外面运行它,消息框永远不会出现。

I think it might be better to listen to the ApplicationExit event. 我认为听一下ApplicationExit事件会更好。 It will prevent the application from actually exiting until the handler is executed: 它将阻止应用程序在执行处理程序之前实际退出:

static void Main()
{
    Application.ApplicationExit += Application_ApplicationExit;

    ...
}

static void Application_ApplicationExit(object sender, EventArgs e)
{
    MessageBox.Show("Exit!");
}
  1. SessionEnding does not fire if you have no window. 如果没有窗口,SessionEnding不会触发。 See http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending%28v=vs.110%29.aspx 请参阅http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionending%28v=vs.110%29.aspx
  2. ProcessExit only has 2 seconds to run. ProcessExit只有2秒的运行时间。 It is too late to display a message box or do anything interactive: http://msdn.microsoft.com/en-us/library/system.appdomain.processexit%28v=vs.110%29.aspx 显示消息框或执行任何交互操作为时已晚: http//msdn.microsoft.com/en-us/library/system.appdomain.processexit%28v=vs.110%29.aspx

I think you either need a service so that it can stay alive after login/logout, or you need to create a window so you have a message pump. 我认为您需要一个服务,以便它可以在登录/注销后保持活动,或者您需要创建一个窗口,以便您有一个消息泵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM