Skip to content

Commit 4fd4c40

Browse files
author
liuchuancong
committed
fix(*)
1 parent 4ac6ea1 commit 4fd4c40

1 file changed

Lines changed: 18 additions & 21 deletions

File tree

lib/common/global/windows_utils.dart

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,56 +8,53 @@ class WindowUtils {
88

99
static bool _findAndWake(int targetId) {
1010
bool found = false;
11+
// 1. 在回调外部分配指针,只分配一次
12+
final propPtr = _propName.toNativeUtf16();
13+
1114
final callback = NativeCallable<WNDENUMPROC>.isolateLocal((int hwnd, int lParam) {
12-
final propPtr = _propName.toNativeUtf16();
15+
// 2. 直接使用外部传入的指针
1316
final val = GetProp(hwnd, propPtr);
14-
free(propPtr);
1517
if (val == targetId) {
16-
// 1. 先检查是否最小化
17-
if (IsIconic(hwnd) != 0) {
18-
ShowWindow(hwnd, SW_RESTORE);
19-
}
18+
if (IsIconic(hwnd) != 0) ShowWindow(hwnd, SW_RESTORE);
2019
ShowWindow(hwnd, SW_SHOW);
2120
SetForegroundWindow(hwnd);
2221
found = true;
23-
return 0; // 停止枚举
22+
return 0;
2423
}
25-
return 1; // 继续
24+
return 1;
2625
}, exceptionalReturn: 0);
2726

2827
try {
2928
EnumWindows(callback.nativeFunction, 0);
3029
} finally {
3130
callback.close();
31+
free(propPtr); // 3. 结束后统一释放
3232
}
33-
3433
return found;
3534
}
3635

37-
/// Mark the current window with the instance hash
3836
static void markCurrentWindow(String instanceId) {
3937
final int idValue = instanceId.isEmpty ? "default".hashCode : instanceId.hashCode;
38+
final propPtr = _propName.toNativeUtf16();
39+
final lpdwProcessId = calloc<Uint32>();
4040

41-
// Find the window belonging to the current process
4241
final callback = NativeCallable<WNDENUMPROC>.isolateLocal((int hwnd, int lParam) {
43-
final lpdwProcessId = calloc<Uint32>();
4442
GetWindowThreadProcessId(hwnd, lpdwProcessId);
4543

46-
// If this window belongs to our PID and is a top-level visible window
4744
if (lpdwProcessId.value == pid && IsWindowVisible(hwnd) != 0) {
48-
final propPtr = _propName.toNativeUtf16();
4945
SetProp(hwnd, propPtr, idValue);
50-
free(propPtr);
51-
free(lpdwProcessId);
52-
return 0; // Found our window, stop
46+
return 0;
5347
}
54-
55-
free(lpdwProcessId);
5648
return 1;
5749
}, exceptionalReturn: 0);
5850

59-
EnumWindows(callback.nativeFunction, 0);
60-
callback.close();
51+
try {
52+
EnumWindows(callback.nativeFunction, 0);
53+
} finally {
54+
callback.close();
55+
free(propPtr);
56+
free(lpdwProcessId); // 确保无论如何都会释放
57+
}
6158
}
6259

6360
static bool wakeUpByProp(String instanceId) {

0 commit comments

Comments
 (0)