2013-06-03 3 views
0

Firefox 탭을 제어하고 싶습니다. URL에 가입하고 브라우저에서 열어 고정 된 매개 변수를 동적으로 생성하는 응용 프로그램이 있습니다.C 파이어 폭스에서 파이어 폭스를 제어하십시오. 마이크로 소프트 인터넷 컨트롤처럼

내 문제는 내가 아래의 코드를 언급하여 C# 응용 프로그램에서 임의의 URL을 열 때, 그것은 항상 같은 탭에서 열린 URL 대신 새 탭을 엽니 다.

Process.Start("firefox", "-url " + newurlscn.Text.ToString()); 

크롬 브라우저에서도이 기능을 원합니다.

IE에서 제대로 작동하는 Internet Explorer 코드가 있지만 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()); 

.

미리 감사드립니다.

+0

을 Firefox에서 완벽하게 제어하려면 Windows UI 자동화를 사용할 수 있습니다. 그런 옵션을 원하니? – qwr

+0

감사합니다. 제가 확인하겠습니다. 브라우저 나 창에 대한 Windows UI 자동화 예제가 있습니까? – user2447637

+0

나는 내가 가진 예를 보냈다. 검사 – qwr

답변

0

firefox .if firefox의 검색 표시 줄 안의이 검색 문자열은 검색 옵션으로 열리지 않습니다. 이미 열었 으면 그것을 앞으로 가져 와서 문자열을 다시 검색 할 것입니다. 원하는 것을 얻기 위해 수정할 수 있습니다. 윈도우 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 
    } 

폴더의 유틸리티 클래스를 참조하는 UI 스파이 도구를 사용하여

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 
0

Selenium Testing Tools를 사용해보십시오. 웹 브라우저/DOM 요소를 완벽하게 제어 할 수 있으며 사용하기가 매우 쉽습니다.

관련 문제