簡體   English   中英

如何在C#應用程序中獲取外部窗口的名稱?

[英]How to get the name of an External window in C# Application?

我在LABVIEW開發了一個簡單的應用程序( .dll ),並將該dll懇請到C#Windows應用程序( Winforms )中。 喜歡

    [DllImport(@".\sample.dll")]
    public static extern void MyFunc(char[] a, StringBuilder b ,Int32 c); 

因此,當我調用函數MyFunc將彈出一個窗口( Lab View窗口(labview應用程序的Front panel

窗口

我需要在我的C#應用​​程序中獲取窗口名稱( ExpectedFuncName )。 即我需要獲取由我的C#應用​​程序打開的外部窗口的名稱。 我們可以使用FileVersionInfoassembly loader來獲取名稱嗎?

有這樣做的主意嗎? 提前致謝。

如果您有窗口句柄,這相對容易:

[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返回的值,但這需要另一個問題...

如果激活LabVIEW腳本(LabVIEW 2010)或進行安裝( LV 8.6,2009),則前面板屬性為FP.nativewindow。 這將使句柄返回到前面板窗口。
使用以下代碼段獲取屬性:
FP.NativeWindow

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM