Ami DATA
Ami DATA

Reputation: 541

Shut Down Dialog From A Thread

I've an application that is running under c# windows form. When the user exit the application, I would like to offer the user to shutdown the computer. My application is a bit complicated but the following is a good example of my problem:

public partial class Form1 : Form
{
    public class shell32
    {
        [DllImport("shell32", EntryPoint = "#60")]
        private static extern int SHShutDownDialog(long p);

        public static void ShutDownDialog()
        {
            int x = SHShutDownDialog(0);
        }
    }

    private Thread _eventHandler;
    private System.Windows.Forms.Button btnShutDown;

    public Form1()
    {
        InitializeComponent();

        AddSDButton();
        SetAndStartThread();
    }

    private void AddSDButton()
    {
        this.btnShutDown = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.btnShutDown.Location = new System.Drawing.Point(50, 50);
        this.btnShutDown.Name = "btnShutDown";
        this.btnShutDown.Size = new System.Drawing.Size(75, 25);
        this.btnShutDown.TabIndex = 0;
        this.btnShutDown.Text = "Shut Down";
        this.btnShutDown.UseVisualStyleBackColor = true;
        this.btnShutDown.Click += new System.EventHandler(this.btnShutDown_Click);

        this.Controls.Add(this.btnShutDown);
    }

    private void SetAndStartThread()
    {
        _eventHandler = new Thread(new ThreadStart(this.EventHandler));
        _eventHandler.IsBackground = true;
        _eventHandler.Start();
    }

    protected void EventHandler()
    {
        try
        {
            while (true)
            {
                //DO SOMETHING..
                Thread.Sleep(5000);
                shell32.ShutDownDialog();
            }
        }
        catch (ThreadAbortException)
        {
            return;
        }
    }

    private void btnShutDown_Click(object sender, EventArgs e)
    {
        shell32.ShutDownDialog();
    }

}

Calling the Shut Down Dialog through the Form by using btnShutDown_Click works fine. However the running thread fails calling the shell32.ShutDownDialog. The SHShutDownDialog returns a negative value. Any ideas?

Upvotes: 2

Views: 187

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61969

You cannot have background threads accessing the UI. The UI must always run on a thread of its own. Your background threads need to post a message to your main thread to ask the main thread to open up the dialog.

For information on how to achieve this type of cross-thread asynchronous message passing, see this question:

How to post a UI message from a worker thread in C#

Upvotes: 3

Related Questions