从线程关闭对话框

时间:2015-02-09 14:32:57

标签: c# winforms

我有一个在c#windows窗体下运行的应用程序。 当用户退出应用程序时,我想让用户关闭计算机。 我的应用程序有点复杂,但以下是我的问题的一个很好的例子:

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

}

使用btnShutDown_Click通过表单调用关闭对话框工作正常。但是,正在运行的线程无法调用shell32.ShutDownDialog。 SHShutDownDialog返回负值。 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您无法让后台线程访问UI。 UI必须始终在自己的线程上运行。您的后台线程需要向主线程发送消息,要求主线程打开对话框。

有关如何实现此类跨线程异步消息传递的信息,请参阅以下问题:

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