Search code examples
c#shutdownapplication-close

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. If i run it outside, the messagebox never appears.


Solution

  • I think it might be better to listen to the ApplicationExit event. 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!");
    }