在c# .net中像微软Internet控件一样控制Firefox
本文关键字:一样 Firefox 控制 控件 net Internet 微软 | 更新日期: 2023-09-27 18:16:46
我想控制Firefox选项卡。我有一个应用程序,动态生成固定url的参数,我加入url并在浏览器上打开。
我的问题是,当我通过下面提到的代码从c#应用程序打开任何url时,它总是打开新选项卡,而不是在相同的可用选项卡上打开url。
Process.Start("firefox", "-url " + newurlscn.Text.ToString());
我希望chrome浏览器也有这个功能。
我有Internet explorer代码,在IE中工作良好,但需要Firefox和chrome的帮助。
IE代码: SHDocVw.ShellWindows pvShell = new ShellWindows();
SHDocVw.InternetExplorer pvWeb2 = null;
SHDocVw.ShellBrowserWindow pvweb3 = null;
int dwCount;
Boolean IsNavigate = false;
if (pvShell.Count > 0)
{
for (dwCount = 0; dwCount < pvShell.Count; dwCount++)
{
var ovIE = pvShell.Item(dwCount);
if (((ovIE.LocationURL.IndexOf("callprocrm.com") > 0) && (ovIE.LocationURL.IndexOf("index.php") > 0)))
{
pvWeb2 = ovIE;
pvWeb2.Navigate(newurlscn.Text, ovIE, ovIE, ovIE, ovIE);
pvWeb2 = null;
IsNavigate = true;
break;
}
}
if (!IsNavigate)
Process.Start("iexplore", newurlscn.Text.ToString());
}
else
Process.Start("iexplore", newurlscn.Text.ToString());
我请求你尽快帮助我。
这个例子在firefox的搜索栏中搜索字符串。如果firefox未打开,它将打开搜索选项。如果它已经打开了,那么它将把它带到前面并再次搜索字符串。你可以修改以达到你想要的效果。使用UI SPY工具实际查看windows UI自动化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Automation;
using Utils;
namespace ControllerX.Executions
{
/// <summary>
/// this class provide searching mechanisms
/// </summary>
class searching
{
public static void search(string Sentence)
{
if ( String.IsNullOrEmpty(Sentence)==true ) return; //no need to search empty value
try
{
searchInFireFox( Sentence);
}
catch (Exception ex)
{
Util.Debuglog(ex.Message);
}//ex
}
private static AutomationElement cached;
private static Process oldproc;
/// <summary>
/// search inside firefox
/// </summary>
/// <param name="search_term"></param>
private static void searchInFireFox(string search_term)
{
//search using firefox
if (oldproc != null && oldproc.HasExited == false && cached!=null )
{
object cachedPattern;
if (true == cached.TryGetCachedPattern(InvokePattern.Pattern, out cachedPattern))
{
InvokePattern iPattern = cachedPattern as InvokePattern ;
Util.BringToFront(oldproc.MainWindowHandle);
if (iPattern != null) { iPattern.Invoke(); Util.SimulateMessage(search_term, true); }
Util.Debuglog("Invoked within cached :" + search_term);
}
return;
}//
Process firefox = null;
if (oldproc != null && oldproc.HasExited == true) { oldproc.Close();}
else { firefox=oldproc;Util.Debuglog("firefox=oldproc"); };
cached = null;
if (firefox==null) firefox = Util.FindByName("firefox");
if (firefox != null)
{
cached = InvokeAndCache(search_term,firefox.MainWindowHandle);
oldproc=firefox;
}//if
else if( open_new(search_term)==false )
Utils.ErrorHandle.notify_user("Could not search with firefox");
}//
private static bool open_new(string search_term)
{
bool ok = false;
Process pfirefox = null;
pfirefox =Util.StartProc(@"firefox.exe" ,
"-new-tab -search '"" + search_term + "'"",
null,
false);
oldproc = pfirefox;
if (pfirefox != null) { ok = true; Util.Debuglog("opened in new : " + search_term); }
return ok;
}//open new
private static AutomationElement InvokeAndCache(string search_term,IntPtr handle)
{
AutomationElement search = null;
try
{
AutomationElement aeDesktop = AutomationElement.RootElement;
AutomationElement aeBrowser = AutomationElement.FromHandle(handle);
// Set up the request.
CacheRequest cacheRequest = new CacheRequest();
cacheRequest.AutomationElementMode = AutomationElementMode.None;
cacheRequest.TreeFilter = Automation.ControlViewCondition;
cacheRequest.Add(AutomationElement.ControlTypeProperty);
cacheRequest.Add(InvokePattern.Pattern);
System.Windows.Automation.Condition conLocation = new OrCondition(
new PropertyCondition(AutomationElement.NameProperty, "Navigation Toolbar"),
new PropertyCondition(AutomationElement.NameProperty, "Панель навигации") );//russian name of the tab
AutomationElement navigation = null;
navigation = aeBrowser.FindFirst(TreeScope.Descendants, conLocation);
cacheRequest.Push();
if (navigation != null)
{
AutomationElementCollection elList = navigation.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
if (elList != null && elList.Count > 1)
search = elList[elList.Count - 1];
}
if (search != null)
{
Util.BringToFront(handle);
InvokePattern iPattern = search.GetCachedPattern(InvokePattern.Pattern) as InvokePattern;
cached = search;
if (iPattern != null) {
iPattern.Invoke();
Util.SimulateMessage(search_term,true); //above what simulateMessage does
// winform.SendKeys.SendWait(message);
// winform.SendKeys.SendWait("{ENTER}");
Util.Debuglog("cached then invoked : " + search_term);
}//if iPattern
}//if
cacheRequest.Pop();
}
catch (Exception ex)
{
Util.Debuglog(ex.Message);
}//try catch
return search;
}
}//end class
}
util类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
//using winform = System.Windows.Forms;
using WindowsInput;
/*
* author:qwr
*
* */
namespace Utils
{
/// <summary>
/// Utility methods for using through the program
/// </summary>
class Util
{
/// <summary>
/// Starting external program
/// </summary>
/// <param name="file_name">path of the executable file</param>
/// <param name="arguments">arguments to be passed </param>
/// <param name="hidden">options for showing windows</param>
/// <returns>return Process if the function succeeds otherwise null</returns>
public static Process StartProc(string file_name, string arguments,string workdir, bool hidden)
{
Process proc = null;
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
if (workdir!=null && workdir.Length>0)
startInfo.WorkingDirectory = workdir;
if (arguments != null && arguments.Length > 0)
startInfo.Arguments = arguments;
startInfo.FileName = file_name;
if (hidden == true)
{
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
}//hidden
proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
Debuglog("startProc started " + file_name);
}//try
catch(Exception ex)
{
Debuglog("startProc " + file_name);
Debuglog("startProc error :"+ ex.Message);
proc = null;
}//try-catch
return proc;
}//startproc
/// <summary>
/// Kill all instances of process by name
/// </summary>
/// <param name="name">name of process</param>
public static void KillProc(string name)
{
Process[] Proclist = Process.GetProcessesByName(name);
foreach (Process proc in Proclist)
{
proc.Kill();
}//for
return;
}//killproc
/// <summary>
/// Kill Process
/// </summary>
/// <param name="process"></param>
public static void KillProc( Process process)
{
try
{
if (process != null && process.HasExited == false)
{
process.Kill();
Util.Debuglog("trying to kill process..."+process.Id);
}//if null
}//try
catch (Exception ex)
{
Util.Debuglog("fail to kill");
ex.Message.toLog();
ex.StackTrace.toLog();
}//try-catch
}
/// <summary>
/// Finds first occurence of the process instance by its name
/// </summary>
/// <param name="name">name of processed that will be searched</param>
/// <returns>return Process on succed otherwise null</returns>
public static Process FindByName(string name)
{
Process found = null;
//need to find through name
Process[] myProcess = Process.GetProcesses();
foreach (Process p in myProcess)
if (p.ProcessName == name) { found = p; break; }
return found;
}
/// <summary>
/// Convert unix time to C# date
/// </summary>
/// <param name="unixTime"></param>
/// <returns></returns>
public static DateTime CSharpTime(double unixTime)
{
DateTime unixStartTime = new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc);
return unixStartTime.AddSeconds(unixTime).ToLocalTime();
}//ToCSharpTime
/// <summary>
/// Makes windows appear on the top
/// </summary>
/// <param name="handle">hadnle of window</param>
public static void BringToFront(IntPtr handle)
{
native.WINDOWPLACEMENT wndP;
native.GetWindowPlacement(handle, out wndP);
if (wndP.ShowCmd == native.WindowShowStyle.ShowMinimized || wndP.ShowCmd == native.WindowShowStyle.Minimize)
native.ShowWindow(handle, native.WindowShowStyle.ShowDefault);
native.SetForegroundWindow(handle);
}
/// <summary>
/// simulating keyboard .
/// </summary>
/// <param name="message">message that will be typed</param>
/// <param name="enterKey">indicates if enter key will be send after message</param>
/// <remarks>this function uses windows.forms.sendkeys.sendwait
/// for better performance you can use other simulators
/// or direct text manipulation methods
/// </remarks>
public static void SimulateMessage(string message, bool enterKey)
{
// winform.SendKeys.SendWait(message); //calls application doevents inside
// if (enterKey) winform.SendKeys.SendWait("{ENTER}");
InputSimulator.SimulateTextEntry(message);
if (enterKey) InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN);
}
private static readonly object locker = new object();
/// <summary>
/// small log . debug only
/// </summary>
/// <param name="s"></param>
// [ConditionalAttribute("DEBUG")]
public static void Debuglog(string s)
{
lock (locker)
using (StreamWriter nm = new StreamWriter("log", true, Encoding.UTF8))
{
nm.Write(DateTime.Now.ToLongTimeString());
nm.Write("--- > ");
nm.WriteLine(s);
}//using
}
}//end class
}//end namespace
尝试使用Selenium Testing Tools
。它可以让你完全控制web浏览器/DOM元素,它非常容易使用。