-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExplorerController.cs
More file actions
104 lines (91 loc) · 2.57 KB
/
ExplorerController.cs
File metadata and controls
104 lines (91 loc) · 2.57 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
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
namespace ClearCacheIcons
{
internal static class ExplorerController
{
private const int WM_CLOSE = 0x0010;
[DllImport("user32.dll")]
private static extern bool PostMessage(
IntPtr hWnd,
int msg,
IntPtr wParam,
IntPtr lParam
);
public static bool IsExplorerRunning()
{
return Process.GetProcessesByName("explorer").Any();
}
public static bool TryCloseExplorerGracefully(int timeoutMs = 5000)
{
var explorers = Process.GetProcessesByName("explorer");
if (explorers.Length == 0)
return true;
foreach (var proc in explorers)
{
try
{
if (proc.MainWindowHandle != IntPtr.Zero)
PostMessage(proc.MainWindowHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
catch
{
// Error recuperable
}
}
return WaitForExplorerExit(timeoutMs);
}
public static bool ForceKillExplorer()
{
try
{
foreach (var proc in Process.GetProcessesByName("explorer"))
{
try
{
proc.Kill(true);
}
catch
{
// Puede fallar en Windows moderno (normal)
}
}
return WaitForExplorerExit(10000); // Keep the 10-second timeout
}
catch
{
return false;
}
}
private static bool WaitForExplorerExit(int timeoutMs)
{
int waited = 0;
while (waited < timeoutMs)
{
if (!IsExplorerRunning())
return true;
Thread.Sleep(250);
waited += 250;
}
return false;
}
public static void RestartExplorer()
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
UseShellExecute = true
});
}
catch
{
// Si falla, Windows normalmente lo relanza solo
}
}
}
}