2010-10-03 39 views
1

我在LABVIEW開發了一個簡單的應用程序(.dll)和我implorted該DLL到C#Windows應用程序(Winforms)。像如何在C#應用程序中獲取外部窗口的名稱?

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

所以當我調用函數MyFunc一個窗口會彈出(在Lab View窗口(Front panel我的LabVIEW應用程序的

Window

我需要得到窗口名稱(ExpectedFuncName)在我的C#應用​​程序。即,我需要得到由我的C#應用​​程序運行結束的對外窗口的名稱。我們可以使用FileVersionInfoassembly loader得到名字?

是否有任何想法要做到這一點? 在此先感謝。

回答

6

如果您有窗口句柄,這是比較容易的:

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

+0

謝謝你......請你解釋一下示例代碼第二種方法。 – 2010-10-03 09:57:51

+0

完成。啓發式部分很簡單,但實際上它應該在編譯時知道所有應用程序窗口標題。 – Luca 2010-10-04 11:04:22

4

如果您激活LabVIEW腳本(的LabVIEW 2010),或安裝(LV 8.6, 2009)有一個叫前面板屬性 'FP.nativewindow'。這會返回前面板窗口的句柄。
使用下面的代碼片段獲取屬性:
FP.NativeWindow

相關問題