我在.dll
中开发了一个简单的应用程序(LABVIEW
),并将该dll恳请到C#Windows应用程序(Winforms
)中。喜欢
[DllImport(@".\sample.dll")]
public static extern void MyFunc(char[] a, StringBuilder b ,Int32 c);
因此,当我调用函数
MyFunc
时,将弹出一个窗口(Labview应用程序的Lab View
窗口(Front panel
我需要在C#应用程序中获取窗口名称(
ExpectedFuncName
)。即我需要获取由我的C#应用程序打开的外部窗口的名称。我们可以使用FileVersionInfo
或assembly 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返回的值,但这需要另一个问题...
关于c# - 如何在C#应用程序中获取外部窗口的名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3849025/