在C#中,可以通過調用EnumChildWindows函數來獲取窗口的句柄,然后使用LINQ對結果進行排序。以下是一個示例代碼:
using System;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
[DllImport("user32.dll")]
public static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildCallback lpEnumFunc, IntPtr lParam);
public delegate bool EnumChildCallback(IntPtr hwnd, IntPtr lParam);
static void Main()
{
List<IntPtr> childWindows = new List<IntPtr>();
EnumChildWindows(Process.GetCurrentProcess().MainWindowHandle, (hwnd, lParam) =>
{
childWindows.Add(hwnd);
return true;
}, IntPtr.Zero);
// 對結果進行排序
var sortedChildWindows = childWindows.OrderBy(hwnd => GetWindowText(hwnd)).ToList();
// 輸出排序后的窗口標題
foreach (var hwnd in sortedChildWindows)
{
Console.WriteLine(GetWindowText(hwnd));
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
static string GetWindowText(IntPtr hWnd)
{
const int nChars = 256;
System.Text.StringBuilder Buff = new System.Text.StringBuilder(nChars);
if (GetWindowText(hWnd, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
}
在上面的示例代碼中,我們通過調用EnumChildWindows函數獲取父窗口的所有子窗口句柄,并使用GetWindowText函數獲取每個子窗口的標題。然后使用LINQ的OrderBy方法對子窗口標題進行排序。最后輸出排序后的子窗口標題。