C# 如何启动WinForms应用程序并使用C代码检查其中是否存在按钮?
我必须制作一个简单的工具,用于执行以下操作:C# 如何启动WinForms应用程序并使用C代码检查其中是否存在按钮?,c#,winforms,process.start,C#,Winforms,Process.start,我必须制作一个简单的工具,用于执行以下操作: 从本地磁盘上的文件启动WinForms应用程序 检查窗口标题是否与预定义字符串匹配 检查应用程序窗口中是否存在按钮 我使用以下代码启动应用程序: Process myApp = new Process(); myApp.StartInfo.FileName = "somePath"; app.Start(somePath); 我使用myApp.MainWindowTitle属性检查窗口名称 我想知道如何检查应用程序窗口中是否存在某些内容,例如确
- 从本地磁盘上的文件启动WinForms应用程序
- 检查窗口标题是否与预定义字符串匹配
- 检查应用程序窗口中是否存在按钮
Process myApp = new Process();
myApp.StartInfo.FileName = "somePath";
app.Start(somePath);
我使用myApp.MainWindowTitle
属性检查窗口名称
我想知道如何检查应用程序窗口中是否存在某些内容,例如确保按钮存在
此工具的目的是仅检查应用程序是否正确启动。我现在正试图弄清楚VisualStudioCodeDui功能到底是什么,以及它如何提供帮助,但到目前为止还没有任何结果
如果有人能给我一些信息和/或想法,我将不胜感激。虽然这是对另一个问题的回答,但您可能会觉得很有帮助。看看他的解决方案的第二部分,他称之为“更难的解决方案”。希望能有所帮助。我从很久以前就开始挖掘陈旧的Delphi代码,并将其翻译成c: 类,该类将枚举所有子窗口:
public static class WindowsEnumerator
{
private static List<IntPtr> childs = new List<IntPtr>();
public static List<WindowInfo> EnumerateChildWindows(IntPtr parentHandle)
{
var result = new List<WindowInfo>();
childs.Clear();
EnumChildWindows(parentHandle, Enumerator, IntPtr.Zero);
foreach (IntPtr handle in childs)
{
result.Add(new WindowInfo(handle));
}
return result;
}
private static bool Enumerator(IntPtr hwnd, IntPtr lparam)
{
childs.Add(hwnd);
return true;
}
internal delegate bool WindowEnumProc(IntPtr hwnd, IntPtr lparam);
[DllImport("user32.dll")]
internal static extern bool EnumChildWindows(IntPtr hwnd, WindowEnumProc func, IntPtr lParam);
}
public class WindowInfo
{
public IntPtr Handle { get; private set; }
public string Text { get; private set; }
public string ClassName { get; private set; }
public WindowInfo(IntPtr hwnd)
{
this.Handle = hwnd;
var sb = new StringBuilder(1024);
var txtLen = GetWindowText(this.Handle, sb, sb.Capacity);
if (txtLen > 0)
this.Text = sb.ToString();
else
this.Text = "";
var sbc = new StringBuilder(256);
var clsLen = GetClassName(this.Handle, sbc, sbc.Capacity);
if (clsLen > 0)
this.ClassName = sbc.ToString();
else
this.ClassName = "";
}
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
}
若应用程序启动不正常,是否会出现一些异常?如果是这样的话,最好记录异常,然后简单地检查登录,这样您就不太可能检测到流程窗口中是否存在按钮。
private void button1_Click(object sender, EventArgs e)
{
var exeProcess = Process.Start(@"w:\kanta\temp\ExeWithButtonInsideGroupBox.exe");
while (exeProcess.MainWindowHandle.ToInt32() == 0)
{
Thread.Sleep(10);
};
var windows = WindowsEnumerator.EnumerateChildWindows(exeProcess.MainWindowHandle);
exeProcess.Kill();
bool myButtonExists = windows.FirstOrDefault(wnd => wnd.ClassName.Contains("BUTTON") && wnd.Text == "button1") != null;
MessageBox.Show(myButtonExists.ToString());
}