自动化测试程序-关于为什么用API不能得到C#菜单问题
//我在编写自动化测试程序时,要获取C#的菜单句柄,可是不知为什么老是得不到(即红字代码部分总是0).//不知那位高手能帮我解决此问题呀?
//程序说明:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IntPtr mwh = FindMainWindowHandle("Form1", 100, 25); //得到Form1窗口句柄
Console.WriteLine("Main window handle = " + mwh);
Thread.Sleep(1000);
IntPtr hMainMenu = GetMenu(mwh);//在这里开始用菜单方法就不行了,没反应执行后
Console.WriteLine("Handle to main menu is " + hMainMenu);
IntPtr a = GetSubMenu(hMainMenu, 0);//a好像没拿到值
int c = GetMenuItemID(a, 0);
uint WM_COMMAND = 0x0111;
SendMessage2(mwh, WM_COMMAND, c, IntPtr.Zero); //执行菜单操作
}
static IntPtr FindTopLevelWindow(string caption, int delay,
int maxTries)
{
IntPtr mwh = IntPtr.Zero;
bool formFound = false;
int attempts = 0;
do
{
mwh = FindWindow(null, caption);
if (mwh == IntPtr.Zero)
{
Console.WriteLine("Form not yet found");
Thread.Sleep(delay);
++attempts;
}
else
{
Console.WriteLine("Form has been found");
formFound = true;
}
} while (!formFound && attempts < maxTries);
if (mwh != IntPtr.Zero)
return mwh;
else
throw new Exception("Could not find Main Window");
} // FindTopLevelWindow()
static IntPtr FindMainWindowHandle(string caption, int delay, int maxTries)
{
return FindTopLevelWindow(caption, delay, maxTries);
}
static Form LaunchApp(string path, string formName)
{
Form result = null;
Assembly a = Assembly.LoadFrom(path);
Type t = a.GetType(formName);
result = (Form)a.CreateInstance(t.FullName);
AppState aps = new AppState(result);
ThreadStart ts = new ThreadStart(aps.RunApp);
Thread thread = new Thread(ts);
thread.Start();
return result;
}
private class AppState
{
public readonly Form formToRun;
public AppState(Form f)
{
this.formToRun = f;
}
public void RunApp()
{
Application.Run(formToRun);
}
} // class AppState
// for WM_COMMAND message
[DllImport("user32.dll", EntryPoint = "SendMessage",
CharSet = CharSet.Auto)]
static extern void SendMessage2(IntPtr hWnd, uint Msg,
int wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "FindWindow",
CharSet = CharSet.Auto)]
static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
// Menu routines
static extern IntPtr GetMenu(IntPtr hWnd);
//
static extern IntPtr GetSubMenu(IntPtr hMenu, int nPos);
//
static extern int GetMenuItemID(IntPtr hMenu, int nPos);
[DllImport("user32.dll", EntryPoint = "FindWindowEx",
CharSet = CharSet.Auto)]
static extern IntPtr FindWindowEx(IntPtr hwndParent,
IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
}
} 您好,我最近也在学习这部分的知识,也遇到了这个问题,很想知道你那边是如何解决,我的联系方式是:272817201,谢谢! 我遇到了同样的问题,希望高手能帮帮忙啊
页:
[1]