Skip to content

Commit f44cc08

Browse files
committed
fix crash on Windows logout
1 parent c1cf752 commit f44cc08

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

GabNetStats/MainForm.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,23 @@ public MainForm()
183183
InitializeComponent();
184184
}
185185

186+
protected override void WndProc(ref Message m)
187+
{
188+
const int WM_QUERYENDSESSION = 0x0011;
189+
const int WM_ENDSESSION = 0x0016;
190+
191+
if (m.Msg == WM_QUERYENDSESSION || m.Msg == WM_ENDSESSION)
192+
{
193+
Program.IsWindowsShuttingDown = true;
194+
// Signal threads to stop and save state cleanly
195+
try { workerCancellationTokenSource.Cancel(); } catch { }
196+
Settings.Default.Save();
197+
m.Result = (IntPtr)1; // Tell Windows: OK to shut down
198+
return;
199+
}
200+
base.WndProc(ref m);
201+
}
202+
186203
private void applyIconSet()
187204
{
188205
string desiredSet = Settings.Default.IconSet;

GabNetStats/Program.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ static class Program
1111
/// </summary>
1212
private static Mutex m_Mutex;
1313

14+
/// <summary>Set to true when Windows initiates a shutdown, to suppress restart on crash.</summary>
15+
public static bool IsWindowsShuttingDown { get; set; }
16+
1417
[STAThread]
1518
static void Main()
1619
{
@@ -30,16 +33,16 @@ static void Main()
3033
}
3134
catch (Exception ex)
3235
{
33-
if (ex.GetType() != typeof(ThreadAbortException))
36+
if (!IsWindowsShuttingDown && ex.GetType() != typeof(ThreadAbortException))
3437
{
3538
MessageBox.Show(
3639
Res.str_ErrorCrash +
3740
"\n\n" + "Thread : " +
3841
Thread.CurrentThread.Name +
3942
"\n\n" +
4043
ex.ToString(), "GabNetStats", MessageBoxButtons.OK, MessageBoxIcon.Error);
44+
Application.Restart();
4145
}
42-
Application.Restart();
4346
}
4447
}
4548
}

GabNetStats/frmBalloon.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,8 +203,12 @@ private void frmBalloon_FormClosing(object sender, FormClosingEventArgs e)
203203
{
204204
counter = 0;
205205
Settings.Default.Save();
206-
e.Cancel = true;
207-
this.Hide();
206+
if (e.CloseReason == CloseReason.UserClosing)
207+
{
208+
e.Cancel = true;
209+
this.Hide();
210+
}
211+
// For WindowsShutDown, ApplicationExitCall, etc., let it close
208212
}
209213

210214
private void frmBalloon_VisibleChanged(object sender, EventArgs e)

0 commit comments

Comments
 (0)