Skip to content

Commit bf2d12f

Browse files
committed
Improve Native Methods
1 parent 5ca73f5 commit bf2d12f

3 files changed

Lines changed: 10 additions & 31 deletions

File tree

dev/DevWinUI/Helpers/PathHelper.cs

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -58,23 +58,13 @@ public static string GetAppDataFolderPath(bool forceUnpackagedMode = false)
5858
/// <returns></returns>
5959
public static string GetExecutablePathNative()
6060
{
61-
const uint MAX_Length = 255;
62-
Span<char> buffer = stackalloc char[(int)MAX_Length];
61+
const int MAX_Length = 255;
62+
Span<char> buffer = stackalloc char[MAX_Length];
63+
var hModule = PInvoke.GetModuleHandle(string.Empty);
64+
SafeHandle safeHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(hModule.DangerousGetHandle(), ownsHandle: false);
6365

64-
unsafe
65-
{
66-
fixed (char* pBuffer = buffer)
67-
{
68-
uint result = PInvoke.GetModuleFileName(HMODULE.Null, new PWSTR(pBuffer), MAX_Length);
69-
70-
if (result == 0)
71-
{
72-
throw new Win32Exception();
73-
}
74-
75-
return new string(pBuffer, 0, (int)result);
76-
}
77-
}
66+
uint result = PInvoke.GetModuleFileName(safeHandle, buffer);
67+
return result > 0 ? buffer.Slice(0, (int)result).ToString() : string.Empty;
7868
}
7969

8070
/// <summary>

dev/DevWinUI/Helpers/WindowHelper/WindowHelper.cs

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -236,21 +236,9 @@ public static string GetWindowText(IntPtr hwnd)
236236
public static string GetClassName(IntPtr hwnd)
237237
{
238238
const int MAX_Length = 256;
239-
Span<char> buffer = stackalloc char[(int)MAX_Length];
240-
241-
unsafe
242-
{
243-
fixed (char* pBuffer = buffer)
244-
{
245-
int result = PInvoke.GetClassName(new HWND(hwnd), pBuffer, MAX_Length);
246-
if (result > 0)
247-
{
248-
string className = new string(pBuffer, 0, result);
249-
return className;
250-
}
251-
}
252-
}
253-
return null;
239+
Span<char> buffer = stackalloc char[MAX_Length];
240+
int result = PInvoke.GetClassName(new HWND(hwnd), buffer);
241+
return result > 0 ? buffer.Slice(0, (int)result).ToString() : string.Empty;
254242
}
255243

256244
/// <summary>

dev/DevWinUI/NativeMethods.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ GetCursorPos
2323
GetDC
2424
GetDpiForWindow
2525
GetModuleFileName
26+
GetModuleHandle
2627
GetMonitorInfo
2728
GetPrivateProfileString
2829
GetStockObject

0 commit comments

Comments
 (0)