-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
588 lines (495 loc) · 19.3 KB
/
Form1.cs
File metadata and controls
588 lines (495 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsErrorChecker
{
public partial class Form1 : Form
{
private System.Windows.Forms.Timer loadingTimer;
private int loadingDots = 1;
private CancellationTokenSource scanCts;
private bool isScanning = false;
// ===========================MOVE-DRAG==========================
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(
IntPtr hWnd,
int Msg,
IntPtr wParam,
IntPtr lParam);
private const int WM_NCLBUTTONDOWN = 0xA1;
private const int HTCAPTION = 0x2;
private void EnableDrag(Control c)
{
c.MouseDown += (s, e) =>
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(this.Handle, WM_NCLBUTTONDOWN,
(IntPtr)HTCAPTION, IntPtr.Zero);
}
};
}
public Form1()
{
InitializeComponent();
EnableDrag(this);
EnableDrag(Title);
linkLabel1.Text = "\uE8BB"; // Close
linkLabel2.Text = "\uE921"; // Minimize
if (this.WindowState == FormWindowState.Normal)
{
linkLabel2.Text = "\uE922"; // Maximize
}
else
{
linkLabel2.Text = "\uE923"; // Restore
}
InitLoading();
this.FormClosing += Form1_FormClosing;
}
// ===========================resize form==========================
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x0084;
const int HTCLIENT = 1;
const int HTLEFT = 10;
const int HTRIGHT = 11;
const int HTTOP = 12;
const int HTTOPLEFT = 13;
const int HTTOPRIGHT = 14;
const int HTBOTTOM = 15;
const int HTBOTTOMLEFT = 16;
const int HTBOTTOMRIGHT = 17;
const int RESIZE_HANDLE_SIZE = 8; // width of resize area
if (m.Msg == WM_NCHITTEST)
{
base.WndProc(ref m);
if ((int)m.Result == HTCLIENT)
{
Point p = PointToClient(new Point(m.LParam.ToInt32()));
bool left = p.X <= RESIZE_HANDLE_SIZE;
bool right = p.X >= ClientSize.Width - RESIZE_HANDLE_SIZE;
bool top = p.Y <= RESIZE_HANDLE_SIZE;
bool bottom = p.Y >= ClientSize.Height - RESIZE_HANDLE_SIZE;
if (left && top) m.Result = (IntPtr)HTTOPLEFT;
else if (right && top) m.Result = (IntPtr)HTTOPRIGHT;
else if (left && bottom) m.Result = (IntPtr)HTBOTTOMLEFT;
else if (right && bottom) m.Result = (IntPtr)HTBOTTOMRIGHT;
else if (left) m.Result = (IntPtr)HTLEFT;
else if (right) m.Result = (IntPtr)HTRIGHT;
else if (top) m.Result = (IntPtr)HTTOP;
else if (bottom) m.Result = (IntPtr)HTBOTTOM;
}
return;
}
base.WndProc(ref m);
}
// ===========================
// LOADING TEXT
// ===========================
private void InitLoading()
{
loading.Visible = false;
labelprogress.Visible = false;
panelProgressBack.Visible = false;
loadingTimer = new System.Windows.Forms.Timer();
loadingTimer.Interval = 400;
loadingTimer.Tick += delegate
{
loadingDots = loadingDots >= 7 ? 1 : loadingDots + 1;
loading.Text = "Loading" + new string('.', loadingDots);
};
}
private void StartLoading()
{
loadingDots = 1;
loading.Text = "Loading.";
loading.Visible = true;
labelprogress.Visible = true;
panelProgressBack.Visible = true;
loadingTimer.Start();
}
private void StopLoading()
{
loadingTimer.Stop();
loading.Visible = false;
labelprogress.Visible = false;
panelProgressBack.Visible = false;
}
private void SetProgress(int percent)
{
// Ensure percent is 0-100
percent = Math.Max(0, Math.Min(100, percent));
panelProgressFill.Width = panelProgressBack.Width * percent / 100;
// Update text
labelprogress.Text = percent + "%";
}
// ===========================
// BUTTON CLICK
// ===========================
private async void button1_Click(object sender, EventArgs e)
{
if (isScanning)
return;
string msg = "Scanning system errors...\r\nPlease wait.";
txtcpu.Text = msg;
txtgpu.Text = msg;
txtram.Text = msg;
txtdisk.Text = msg;
scanCts = new CancellationTokenSource();
isScanning = true;
StartLoading();
SetScanButtonState(button1, true);
SetProgress(0);
var progress = new Progress<int>(value =>
{
SetProgress(value);
});
try
{
var result = await Task.Run(() => ScanErrors(scanCts.Token, progress), scanCts.Token);
txtcpu.Text = !string.IsNullOrEmpty(result.cpu) ? result.cpu : "No CPU errors detected.";
txtram.Text = !string.IsNullOrEmpty(result.ram) ? result.ram : "No RAM errors detected.";
txtdisk.Text = !string.IsNullOrEmpty(result.disk) ? result.disk : "No Disk errors detected.";
txtgpu.Text = !string.IsNullOrEmpty(result.gpu) ? result.gpu : "No GPU errors detected.";
}
catch (OperationCanceledException)
{
txtcpu.Text = "Scan cancelled.";
txtgpu.Text = "Scan cancelled.";
txtram.Text = "Scan cancelled.";
txtdisk.Text = "Scan cancelled.";
}
finally
{
StopLoading();
SetScanButtonState(button1, false);
SetProgress(100);
isScanning = false;
if (scanCts != null)
{
scanCts.Dispose();
scanCts = null;
}
}
}
// ===========================
// FORM CLOSING
// ===========================
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!isScanning)
return;
DialogResult r = MessageBox.Show(
"Scan is still running.\r\nForce exit?",
"Warning",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (r == DialogResult.No)
{
e.Cancel = true;
return;
}
if (scanCts != null)
scanCts.Cancel();
}
// ===========================Mouse DOWN DISABLE BUTTON ==========================
private void SetScanButtonState(Button btn, bool scanning)
{
btn.ForeColor = scanning
? Color.FromArgb(0, 174, 219)
: Color.White;
btn.BackColor = scanning
? Color.FromArgb(40, 45, 55)
: Color.FromArgb(30, 36, 44);
btn.Cursor = scanning
? Cursors.No
: Cursors.Hand;
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (isScanning)
((Control)sender).Capture = false;
}
// ===========================
// SCAN EVENT LOG
// ===========================
private (string cpu, string ram, string disk, string gpu) ScanErrors(CancellationToken token, IProgress<int> progress)
{
StringBuilder cpu = new StringBuilder();
StringBuilder ram = new StringBuilder();
StringBuilder disk = new StringBuilder();
StringBuilder gpu = new StringBuilder();
try
{
EventLog log = new EventLog("System");
int total = log.Entries.Count;
int processed = 0;
foreach (EventLogEntry e in log.Entries)
{
token.ThrowIfCancellationRequested();
string src = e.Source.ToLower();
string msg = e.Message.ToLower();
if (e.EntryType == EventLogEntryType.Error || e.EntryType == EventLogEntryType.Warning)
{
if (e.Source == "BugCheck")
cpu.AppendLine(FormatBugCheck(e));
else if (src.Contains("whea"))
cpu.AppendLine(Format(e));
else if (src.Contains("memory") || msg.Contains("page fault"))
ram.AppendLine(Format(e));
else if (src.Contains("disk") || src.Contains("stor") || msg.Contains("bad block"))
{
string diskLog = FormatDisk(e);
if (!string.IsNullOrEmpty(diskLog))
disk.AppendLine(diskLog);
}
else if (src.Contains("nvlddmkm") || src.Contains("amdkmdag") || msg.Contains("tdr"))
gpu.AppendLine(FormatGpu(e));
}
processed++;
// Update progress in percent
progress?.Report((int)((processed / (float)total) * 100));
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Some system logs require administrator privileges to read.", "Access Denied",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
return (cpu.ToString(), ram.ToString(), disk.ToString(), gpu.ToString());
}
// ===========================
// BUGCHECK
// ===========================
private string FormatBugCheck(EventLogEntry e)
{
string code = ExtractBugCheckCode(e.Message);
return
"[" + e.TimeGenerated + "]\r\n" +
"Source : BugCheck\r\n" +
"Code : " + code + "\r\n" +
new string('-', 60) + "\r\n";
}
private string ExtractBugCheckCode(string msg)
{
Match m = Regex.Match(msg, @"0x[0-9a-fA-F]{8}");
return m.Success ? m.Value.ToUpper() : "UNKNOWN";
}
// ===========================
// FORMAT COMMON
// ===========================
private string Format(EventLogEntry e)
{
return
"[" + e.TimeGenerated + "]\r\n" +
"Source : " + e.Source + "\r\n" +
"Event ID : " + e.InstanceId + "\r\n" +
e.Message + "\r\n" +
new string('-', 60) + "\r\n";
}
// ===========================
// GPU
// ===========================
private string FormatGpu(EventLogEntry e)
{
StringBuilder sb = new StringBuilder();
// Get all GPUs
List<string> gpuNames = new List<string>();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_VideoController");
foreach (ManagementObject gpu in searcher.Get())
{
gpuNames.Add(gpu["Name"].ToString());
}
}
catch { }
string matchedGpu = "Unknown GPU";
foreach (string name in gpuNames)
{
if (e.Source.ToLower().Contains(name.ToLower()) || e.Message.ToLower().Contains(name.ToLower()))
{
matchedGpu = name;
break;
}
}
sb.AppendLine("[" + e.TimeGenerated + "]");
sb.AppendLine("GPU Device : " + matchedGpu);
sb.AppendLine("Source : " + e.Source);
sb.AppendLine("Event : " + e.InstanceId);
sb.AppendLine(e.Message);
sb.AppendLine(new string('-', 60));
return sb.ToString();
}
// ===========================
// DISK
// ===========================
private string FormatDisk(EventLogEntry e)
{
string diskInfo = GetDiskInfo(e.Message);
// Ignore log if diskInfo is null → brand unknown / disk likely not attached
if (diskInfo == null)
return null;
StringBuilder sb = new StringBuilder();
sb.AppendLine("[" + e.TimeGenerated + "]");
sb.AppendLine("Source : " + e.Source);
sb.AppendLine("Event : " + e.InstanceId);
sb.AppendLine(diskInfo);
sb.AppendLine(e.Message);
sb.AppendLine(new string('-', 60));
return sb.ToString();
}
private string GetDiskInfo(string msg)
{
Match m = Regex.Match(msg, @"harddisk(\d+)", RegexOptions.IgnoreCase);
if (!m.Success)
return null; // do not process if index not found
int index = int.Parse(m.Groups[1].Value);
try
{
// Get physical disk from WMI
ManagementObjectSearcher diskSearcher =
new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Index=" + index);
foreach (ManagementObject disk in diskSearcher.Get())
{
string status = disk["Status"]?.ToString() ?? "UNKNOWN";
string model = disk["Model"]?.ToString() ?? "Unknown Model";
// Ignore disks with Unknown or Pred Fail status
if (status.Equals("Unknown", StringComparison.OrdinalIgnoreCase) ||
status.Equals("Pred Fail", StringComparison.OrdinalIgnoreCase))
return null; // disk will not be displayed
// Get drive letters if any
string driveLetters = GetDriveLetters(disk);
return $"Disk Index : {index}\r\nModel : {model}\r\nStatus : {status}\r\nDrive : {driveLetters}";
}
}
catch
{
// If WMI fails → assume disk not attached
return null;
}
// If disk not found in WMI → likely not attached
return null;
}
// Helper to get drive letters from physical disk
private string GetDriveLetters(ManagementObject disk)
{
List<string> letters = new List<string>();
try
{
// Connect DiskDrive → Partition → LogicalDisk
ManagementObjectSearcher partitionSearcher = new ManagementObjectSearcher(
$"ASSOCIATORS OF {{Win32_DiskDrive.DeviceID='{disk["DeviceID"]}'}} WHERE AssocClass = Win32_DiskDriveToDiskPartition");
foreach (ManagementObject partition in partitionSearcher.Get())
{
ManagementObjectSearcher logicalSearcher = new ManagementObjectSearcher(
$"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{partition["DeviceID"]}'}} WHERE AssocClass = Win32_LogicalDiskToPartition");
foreach (ManagementObject logical in logicalSearcher.Get())
{
letters.Add(logical["DeviceID"].ToString()); // e.g.: C:, D:
}
}
}
catch { }
return letters.Count > 0 ? string.Join(", ", letters) : "Unknown";
}
private void CPU_Click(object sender, EventArgs e)
{
txtcpu.BringToFront();
CPU.FlatStyle = FlatStyle.Flat;
}
private void GPU_Click(object sender, EventArgs e)
{
txtgpu.BringToFront();
GPU.FlatStyle = FlatStyle.Flat;
}
private void RAM_Click(object sender, EventArgs e)
{
txtram.BringToFront();
RAM.FlatStyle = FlatStyle.Flat;
}
private void DISK_Click(object sender, EventArgs e)
{
txtdisk.BringToFront();
DISK.FlatStyle = FlatStyle.Flat;
}
private void CPU_Leave(object sender, EventArgs e)
{
CPU.FlatStyle = FlatStyle.Popup;
}
private void GPU_Leave(object sender, EventArgs e)
{
GPU.FlatStyle = FlatStyle.Popup;
}
private void RAM_Leave(object sender, EventArgs e)
{
RAM.FlatStyle = FlatStyle.Popup;
}
private void DISK_Leave(object sender, EventArgs e)
{
DISK.FlatStyle = FlatStyle.Popup;
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
this.WindowState = FormWindowState.Maximized;
linkLabel2.Text = "\uE923"; // Restore
}
else
{
this.WindowState = FormWindowState.Normal;
linkLabel2.Text = "\uE922"; // Maximize
}
}
private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (!isScanning)
this.Close();
DialogResult r = MessageBox.Show(
"Scan is still running.\r\nForce exit?",
"Warning",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (r == DialogResult.No)
{
return;
}
if (scanCts != null)
scanCts.Cancel();
this.Close();
}
private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string url = "https://github.com/unamed666/WindowsErrorChecker";
try
{
System.Diagnostics.Process.Start(new ProcessStartInfo
{
FileName = url,
UseShellExecute = true // Open in default browser
});
}
catch (Exception ex)
{
MessageBox.Show("Failed to open link: " + ex.Message);
}
}
}
}