2
我有一個在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返回一個負值。 任何想法?
你可以發佈你正在使用的後臺線程的代碼? – 2015-02-09 14:36:14
請解釋發生了什麼?任何異常,只是不關閉對話框? – BoeseB 2015-02-09 14:39:10
我已更新該問題。 – 2015-02-16 13:24:10