2016-09-01 5 views
-2

Visual Studio 2013の実行プロセスがあります。私はデスクトップアプリケーションからフォーカスを設定したいと思います。私のコード -C#の別のプログラムにフォーカスを動的に設定しました

Process[] arrProcesses = Process.GetProcessesByName(strProcessName); 
if (arrProcesses.Length > 0) 
{ 
    IntPtr ipHwnd = arrProcesses[0].MainWindowHandle; 
    Thread.Sleep(100); 
    SetForegroundWindow(ipHwnd); 
} 

私はstrProcessNameとしてMicrosoft Visual Studio 2013 (32 bit)Microsoft Visual Studio 2013Microsoft Visual Studioを試してみました。しかし、どれもうまくいきません。

助けが必要ですか?

+0

Ok。したがって、arrProcesses配列の長さはゼロになると言っていますか? – RBT

+1

プロセス名が間違っている可能性があります - 同様の名前があるかどうかを確認するプロセスを印刷してみてください。 – ydoow

答えて

1

あなたはMicrosoft.VisualBasicへの参照を追加し、AppActivate

Microsoft.VisualBasic.Interaction.AppActivate("Visual"); 

更新

AppActivateは、そのタイトル(titleパラメータは、少なくとも3を必要とするタイトルパラメータを指定して起動するだけで、メインウィンドウを見つけてみてくださいすることができます文字)が表示されますが、Visual Studioのメインウィンドウタイトルは通常Solution Name - Microsoft Visual Studioのようなものなので、ソリューション名または

var processes = Process.GetProcessesByName("devenv"); 
if(processes.Any()) 
    Microsoft.VisualBasic.Interaction.AppActivate(processes[0].MainWindowTitle); 
+0

プロセス{0}が見つかりません。 –

+0

@ s.k.paul check update – Slai

+0

最終的には動作しています。ありがとう&+1。 –

1
[DllImport("USER32.DLL")] 
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

    [DllImport("USER32.DLL")] 
    public static extern bool SetForegroundWindow(IntPtr hWnd); 

    private void FindAppSetFocusAndSendKeyStrokes() 
    { 
     TryFindWindowAndSetFocus("ThunderRT6FormDC", "Human Resource Management System"); 
     SendKeyStrokes("%ML{ENTER}"); 
    } 

    private void TryFindWindowAndSetFocus(string strClassName, string strCaption)//If you can't find strClassName, use String.Empty instead. 
    { 
     Thread.Sleep(1000); 
     int intCounter = 0; 
     IntPtr processHandler = FindWindow(strClassName, strCaption); 

     while (processHandler == IntPtr.Zero) 
     { 
      if (intCounter > 9) 
       break; 

      Thread.Sleep(1000); 
      processHandler = FindWindow(strClassName, strCaption); 
      intCounter++; 
     } 
     if (processHandler == IntPtr.Zero) 
      throw new Exception("Could not find the Process Window"); 

     intCounter = 0; 
     while (!SetForegroundWindow(processHandler)) 
     { 
      if (intCounter > 9) 
       break; 

      Thread.Sleep(500); 
      intCounter++; 
     } 
     if (intCounter > 9) 
      throw new Exception("Could not set Process foreground window"); 
    } 
    private void SendKeyStrokes(string strKeys) 
    { 
     Thread.Sleep(100); 
     SendKeys.SendWait(strKeys); 
     SendKeys.Flush(); 
    } 
関連する問題