如果您有窗口句柄,這是比較容易的:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern int GetWindowTextLength(IntPtr hWnd);
...
int len;
// Window caption
if ((len = GetWindowTextLength(WindowHandle)) > 0) {
sb = new StringBuilder(len + 1);
if (GetWindowText(WindowHandle, sb, sb.Capacity) == 0)
throw new Exception(String.Format("unable to obtain window caption, error code {0}", Marshal.GetLastWin32Error()));
Caption = sb.ToString();
}
這裏,「WindowHandle」是創建的窗口的句柄。
如果你沒有窗口句柄(我看你沒有),你必須枚舉每個桌面頂級窗口,通過創建過程來篩選它們(我看到窗口是由你的應用程序創建的通過調用MYFUNC,所以你知道進程的ID [*]),然後使用啓發式,以確定所需的信息。
這裏是你們的情況下使用你沒有手柄功能的C#進口:
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
基本上EnumWindows的調用EnumWindowsProc在當前桌面找到的每個窗口。所以你可以得到窗口標題。
List<string> WindowLabels = new List<string>();
string GetWindowCaption(IntPtr hWnd) { ... }
bool MyEnumWindowsProc(IntPtr hWnd, IntPtr lParam) {
int pid;
GetWindowThreadProcessId(hWnd, out pid);
if (pid == Process.GetCurrentProcess().Id) {
// Window created by this process -- Starts heuristic
string caption = GetWindowCaption(hWnd);
if (caption != "MyKnownMainWindowCaption") {
WindowLabels.Add(caption);
}
}
return (true);
}
void DetectWindowCaptions() {
EnumWindows(MyEnumWindowsProc, IntPtr.Zero);
foreach (string s in WindowLabels) {
Console.WriteLine(s);
}
}
[*]在這種情況下不是由您的應用程序(即但從另一個後臺進程)創建的窗口,你必須使用過濾另一個進程ID由GetWindowThreadProcessId返回的值,但是這需要另外一個問題.. 。
謝謝你......請你解釋一下示例代碼第二種方法。 – 2010-10-03 09:57:51
完成。啓發式部分很簡單,但實際上它應該在編譯時知道所有應用程序窗口標題。 – Luca 2010-10-04 11:04:22