2016-01-15 00:24:09 +08:00
|
|
|
// //declarations
|
|
|
|
using System; // For IntPtr
|
|
|
|
using System.Runtime.InteropServices; // DllImport
|
|
|
|
using System.Diagnostics; // Process
|
|
|
|
// using System.Windows.Automation; // UIAutomationClient.dll
|
|
|
|
// using System.Threading; // For Thread.Sleep
|
2016-01-14 04:32:17 +08:00
|
|
|
|
|
|
|
class Program
|
|
|
|
{
|
2016-01-15 00:24:09 +08:00
|
|
|
//dll import (can't be in method, but needs to be in class
|
|
|
|
[DllImport("user32.dll")]
|
|
|
|
public static extern void SwitchToThisWindow(IntPtr hWnd);
|
2016-01-14 04:32:17 +08:00
|
|
|
static void Main()
|
|
|
|
{
|
2016-01-15 00:24:09 +08:00
|
|
|
// --------------------------------------------------------------------------------
|
|
|
|
// ---
|
|
|
|
// --------------------------------------------------------------------------------
|
|
|
|
String procName = "MATLAB";
|
2016-01-14 04:32:17 +08:00
|
|
|
//function which calls switchWindow() is here but not important
|
2016-01-15 00:24:09 +08:00
|
|
|
// //
|
|
|
|
Process[] procs = Process.GetProcessesByName(procName);
|
|
|
|
int nProcs = procs.Length;
|
|
|
|
if (nProcs < 1) {
|
|
|
|
Console.WriteLine("No process found for name: {0}", procName);
|
|
|
|
}else{
|
|
|
|
// We'll use the first window we found
|
|
|
|
Process proc=procs[0];
|
|
|
|
if (nProcs >1) {
|
|
|
|
Console.WriteLine("{0} processes found with name: {0}",nProcs,procName);
|
|
|
|
Console.WriteLine("Using first process:");
|
|
|
|
Console.WriteLine("Process Name: {0} ID: {1} Title: {2}", proc.ProcessName, proc.Id, proc.MainWindowTitle);
|
|
|
|
}
|
|
|
|
// --- Switching to window using user32.dll function
|
2016-01-14 04:32:17 +08:00
|
|
|
SwitchToThisWindow(proc.MainWindowHandle);
|
|
|
|
|
2016-01-15 00:24:09 +08:00
|
|
|
// --- Alternative method using AutomationElement
|
|
|
|
// AutomationElement element = AutomationElement.FromHandle(proc.MainWindowHandle);
|
|
|
|
// if (element != null) { element.SetFocus(); }
|
|
|
|
} // Proc Window found
|
2016-01-14 04:32:17 +08:00
|
|
|
}
|
|
|
|
}
|