public static void BringWindowToFront(int processid) { //get the process System.Diagnostics.Process bProcess = System.Diagnostics.Process.GetProcessById(processid);// FirstOrDefault<System.Diagnostics.Process>; //check if the process is nothing or not. if (bProcess != null) { //get the (int) hWnd of the process IntPtr hwnd = bProcess.MainWindowHandle; //check if its nothing if (hwnd != IntPtr.Zero) { //if the handle is other than 0, then set the active window bProcess.WaitForInputIdle(); SetForegroundWindow(hwnd); } else { //we can assume that it is fully hidden or minimized, so lets show it! bProcess.WaitForInputIdle(); ShowWindow(hwnd, ShowWindowEnum.Restore); SetForegroundWindow(hwnd); } } else { //tthe process is nothing, so start it //System.Diagnostics.Process.Start(@"C:\Program Files\B\B.exe"); } }
public Window(Process p, string className, string rootElementName) { this.p = p; IntPtr h = p.Handle; while (h == IntPtr.Zero || !p.Responding) { Sleep(1000); p.WaitForInputIdle(); h = p.Handle; if (p.HasExited) { throw new InvalidOperationException(string.Format("Process '{0}' has exited!", p.StartInfo.FileName)); } } p.WaitForInputIdle(); p.Exited += new EventHandler(OnExited); int id = p.Id; if (this.acc == null) { // p.MainWindowHandle always returns 0 for some unknown reason... int retries = 20; while (retries-- > 0 && this.acc == null) { this.acc = FindWindowForProcessId(id, className, rootElementName); Sleep(1000); } if (this.acc == null) { throw new Exception("Process as no window handle"); } this.handle = this.acc.Hwnd; } }
public void Init() { CheckDisposed(); m_proc = Process.Start(@"DummyTestExe.exe"); m_proc.WaitForInputIdle(); while (Process.GetProcessById(m_proc.Id).MainWindowHandle == IntPtr.Zero) Thread.Sleep(100); m_proc.WaitForInputIdle(); Win32.SetForegroundWindow(m_proc.MainWindowHandle); m_ah = new AccessibilityHelper(m_proc.MainWindowHandle); }
public void Init() { string tePath = SIL.FieldWorks.Common.Utils.DirectoryFinder.GetFWCodeFile(@"\..\Output\Debug\TE.exe"); m_proc = Process.Start(tePath); m_proc.WaitForInputIdle(); while (Process.GetProcessById(m_proc.Id).MainWindowHandle == IntPtr.Zero) Thread.Sleep(100); m_proc.WaitForInputIdle(); Win32.SetForegroundWindow(m_proc.MainWindowHandle); m_ah = new AccessibilityHelper(m_proc.MainWindowHandle); }
public string Run(string command) { if (_State == State.Idle) { _Process = new Process(); _Process.StartInfo = new ProcessStartInfo("cmd", "/c " + command) { RedirectStandardOutput = true, RedirectStandardInput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = false }; _Process.OutputDataReceived += new DataReceivedEventHandler(DataReceived); _Process.Start(); _Process.BeginOutputReadLine(); while(_Process.WaitForInputIdle()) { _State = State.Waiting; } } string output = ""; /* string output = ">>" + command + "\n"; output += _Process.StandardOutput.ReadToEnd(); string error = _Process.StandardError.ReadToEnd(); output += error; output += "\n";*/ _Process.WaitForExit(); _Process.Close(); _State = State.Idle; return output; }
public override void performAUTAutomation(System.Diagnostics.Process processClass) { TestFramework.Log.Log.printSuccess("ATTACHING TO PROCESS:", processClass.Id.ToString( )); System.Threading.Thread.Sleep(500); // Set Word to be the foreground window... Holodeck.Base.SetForegroundWindow(processClass.MainWindowHandle); SendKeyStrokes("The quick brown fox jumped over the lazy dog.", processClass); SendKeyStrokes("{HOME}", processClass); // move cursor to start of line. SendKeyStrokes("+{END}", processClass); // select all the text. SendKeyStrokes("^C", processClass); // copy the text. // Paste the text 200 times. for (int count = 0; count < 200; count++) { SendKeyStrokes("^V", processClass); } // We must wait for input idle, otherwise word will close instantly... processClass.WaitForInputIdle( ); // Sleep a few seconds just to make sure things have some buffer... System.Threading.Thread.Sleep(3000); }
public override void Execute(TestState ts) { bool fStarted = true; string fullPath = m_path + @"\" + m_exeName; // if the app is already running, close it first AppHandle app = Application; if (app != null && app.ExePath == fullPath) { if (app.Process != null) { app.Process.Kill(); app.Process.WaitForExit(3000); } } m_proc = Process.Start(fullPath); if (m_proc == null) fStarted = false; m_proc.WaitForInputIdle(); while (Process.GetProcessById(m_proc.Id).MainWindowHandle == IntPtr.Zero) Thread.Sleep(100); if (m_proc.HasExited) fStarted = false; m_proc.WaitForInputIdle(); Win32.SetForegroundWindow(m_proc.MainWindowHandle); Assertion.AssertEquals(true, fStarted); Assertion.AssertNotNull("Null process", m_proc); Assertion.AssertNotNull("Null window handle", m_proc.MainWindowHandle); }
public static void StartIfNotRunning() { foreach (var process in Process.GetProcesses()) { if (process.ProcessName == "scktsrvr") return; } var newProcess = new Process(); newProcess.StartInfo = new ProcessStartInfo() { FileName = GetSocketServerPath() }; newProcess.Start(); newProcess.WaitForInputIdle(1000); for (int i = 0; i < 100; i++) { foreach (var process in Process.GetProcesses()) { if (process.ProcessName == "scktsrvr") { return; } } Thread.Sleep(100); } Logger.Error("NativeFiresecClient.StartSocketServerIfNotRunning не удалось запустить процесс scktsrvr"); }
/// <summary> /// Main constructor /// </summary> /// <param name="p">the client's process object</param> public Client(Process p) { Process = p; Process.Exited += new EventHandler(process_Exited); Process.EnableRaisingEvents = true; // Wait until we can really access the process Process.WaitForInputIdle(); while (Process.MainWindowHandle == IntPtr.Zero) { Process.Refresh(); System.Threading.Thread.Sleep(5); } // Save a copy of the handle so the process doesn't have to be opened // every read/write operation Handle = Util.WinAPI.OpenProcess(Util.WinAPI.PROCESS_ALL_ACCESS, 0, (uint)Process.Id); PathFinder = new Pokemon.Util.AStarPathFinder(this); Inventory = new Objects.Inventory(this); BattleList = new Objects.BattleList(this); Map = new Objects.Map(this); Memory = new MemoryHelper(this); Window = new Window(this); IO = new IOHelper(this); Login = new LoginHelper(this); Dll = new DllHelper(this); Input = new InputHelper(this); Player = new PlayerHelper(this); // Save the start time (it isn't changing) startTime = Memory.ReadInt32(Addresses.Client.StartTime); }
public static bool LaunchVisualStudio(string Arguments, out string ErrorMessage) { ErrorMessage = ""; VisualStudioInstallation Install = VisualStudioInstallations.GetPreferredInstallation(); if (Install == null) { ErrorMessage = string.Format("Unable to get Visual Studio installation"); return(false); } try { System.Diagnostics.Process VSProcess = new System.Diagnostics.Process { StartInfo = new ProcessStartInfo(Install.DevEnvPath, Arguments) }; VSProcess.Start(); VSProcess.WaitForInputIdle(); } catch (Exception Ex) { ErrorMessage = Ex.Message; return(false); } return(true); }
protected override void OnStart(string[] args) { var exePath = GetExeLocation(args); if (!File.Exists(exePath)) { var message = string.Format("The file {0} could not be found.", exePath); this.EventLog.WriteEntry(message, EventLogEntryType.Error); Environment.Exit(1); } ProcessStartInfo psi = new ProcessStartInfo(exePath); psi.UseShellExecute = true; psi.CreateNoWindow = true; psi.WindowStyle = ProcessWindowStyle.Hidden; try { this.process = Process.Start(psi); if (this.process != null) { process.WaitForInputIdle(); } } catch (Exception ex) { var message = string.Format("Executing the utorrent.exe failed: {0}", ex); this.EventLog.WriteEntry(message, EventLogEntryType.Error); Environment.Exit(2); } }
private void pbButton_Click(object sender, EventArgs e) { RunApp r = new RunApp(); contentPath = @"D:\workspace\of_v0.8.4_vs_release\apps\PegasusHighwaysHotelKidsZone\bin\PegasusHighwaysHotelLauncher\PegasusHighwaysHotelLauncher.exe"; ProcessStartInfo contentInfo = new ProcessStartInfo(); contentInfo.FileName = contentPath; contentInfo.WorkingDirectory = Path.GetDirectoryName(contentPath); contentInfo.UseShellExecute = true; contentInfo.CreateNoWindow = true; contentInfo.WindowStyle = ProcessWindowStyle.Maximized; contentInfo.RedirectStandardInput = false; contentInfo.RedirectStandardOutput = false; contentInfo.RedirectStandardError = false; content = Process.Start(contentInfo); content.WaitForInputIdle(); SetParent(content.MainWindowHandle, this.Handle); content.EnableRaisingEvents = true; content.Exited += Content_Exited; while (!content.Responding) { Game_Loaded(); } }
public Window(Process p) { this.p = p; IntPtr h = p.Handle; while (h == IntPtr.Zero || !p.Responding) { Sleep(1000); p.WaitForInputIdle(); h = p.Handle; if (p.HasExited) { throw new InvalidOperationException(string.Format("Process '{0}' has exited!", p.StartInfo.FileName)); } } p.Exited += new EventHandler(OnExited); int id = p.Id; if (handle == IntPtr.Zero) { // p.MainWindowHandle always returns 0 for some unknown reason... int retries = 20; while (retries-- > 0 && handle == IntPtr.Zero) { handle = FindWindowForProcessId(id); Sleep(1000); } if (handle == IntPtr.Zero) { throw new Exception("Process as no window handle"); } } this.acc = SystemAccessible.AccessibleObjectForWindow(handle); }
static void Main(string[] args) { string CurrentDirectory = System.Environment.CurrentDirectory.Replace("MessageCommunicationA", _messageTo); bool isStart = false; foreach (Process p in Process.GetProcessesByName(_messageTo)) { isStart = true; WinMessageHelper.Send(p.MainWindowHandle.ToInt32(), _messageStr); } if (!isStart) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = _messageTo + ".exe"; process.StartInfo.WorkingDirectory = CurrentDirectory; process.StartInfo.CreateNoWindow = false; process.Start(); process.WaitForInputIdle(); System.Threading.Thread.Sleep(2000); //增加了延时2秒,这样就可以获取计算器的窗口句柄 foreach (Process p in Process.GetProcessesByName(_messageTo)) { WinMessageHelper.Send(p.MainWindowHandle.ToInt32(), _messageStr); } } }
public void RunAndPrintNotepad() { Process notepad = new Process(); notepad.StartInfo.FileName = "notepad.exe"; notepad.Start(); notepad.WaitForInputIdle(); SendKeys.SendWait(StringExample); PrintDocument(); }
public void should_print_and_save_notepad_file() { //arrange string path = @"E:\test.txt"; if (File.Exists(path)) { File.Delete(path); } //act Process excelProc = new Process(); excelProc.StartInfo.FileName = "notepad.exe"; excelProc.Start(); excelProc.WaitForInputIdle(); TestStack.White.Application app = TestStack.White.Application.Attach("notepad"); var wndMain = app.GetWindows()[0]; SendKeys.SendWait("Some Text For Printing and Saving"); Thread.Sleep(200); //Call Print Dialog SendKeys.SendWait("^{p}"); //Print ClickBtn(FindWnd(app), "1"); //Cancel ClickBtn(FindWnd(app), "2"); //Abort Accept ClickBtn(FindWnd(app), "2"); //Call Save Dialog SendKeys.SendWait("^{s}"); var saveDlg = FindWnd(app); var list = saveDlg.Get<TestStack.White.UIItems.TreeItems.Tree>(SearchCriteria.ByAutomationId("100")); var desktop = list.Nodes[1]; desktop.Expand(); var thisPC = desktop.Nodes[2]; thisPC.Expand(); var diskC = thisPC.Nodes.FirstOrDefault(n => n.Text == "Локальный диск (E:)"); diskC.Select(); var fileName = saveDlg.Get<TestStack.White.UIItems.TextBox>(SearchCriteria.ByAutomationId("1001")); fileName.Text = "test"; var btnSave = saveDlg.Get<TestStack.White.UIItems.Button>(SearchCriteria.ByAutomationId("1")); btnSave.Click(); SendKeys.SendWait("%{F4}"); excelProc.WaitForExit(); bool res = File.Exists(path); //assert Assert.AreEqual(true, res); }
public static void LoadProcessInControl(string Process, Control Control) { var startInfo = new ProcessStartInfo(); startInfo.WorkingDirectory = Path.GetDirectoryName(@Process); startInfo.FileName = @Process; System.Diagnostics.Process p = System.Diagnostics.Process.Start(startInfo); p.WaitForInputIdle(); SetParent(p.MainWindowHandle, Control.Handle); }
private void button2_Click(object sender, EventArgs e) { //启动notepad.exe 记事本程序,并在d:\下创建 或 打开 text_test.txt文件 System.Diagnostics.Process txt = System.Diagnostics.Process.Start(@"notepad.exe", @"d:\text_test.txt"); txt.StartInfo.WindowStyle = ProcessWindowStyle.Normal; //等待一秒,以便目标程序notepad.exe输入状态就绪 txt.WaitForInputIdle(1000); //如果目标程序 notepad.exe 没有停止响应,则继续 if (txt.Responding) { //开始写入内容 SendKeys.SendWait("-----下面的内容是外部程序自动写入-----\r\n"); SendKeys.SendWait("heihei"); //将文本框内的内容写入 SendKeys.SendWait("{Enter}{Enter}"); //写入2个回车 SendKeys.SendWait("文档创建时间:"); SendKeys.SendWait("{F5}"); //发送F5按键 SendKeys.SendWait("{Enter}"); //发送回车键 //NativeMethods.SetForegroundWindow(txt.Handle); //StringBuilder sb = new StringBuilder(); //NativeMethods.GetWindowText(txt.Handle, sb, 256); for (int i = 0; i < 10; i++) { Win32API.KeyDown(Keys.F5); Win32API.KeyUp(Keys.F5); Win32API.KeyDown(Keys.Enter); Win32API.KeyUp(Keys.Enter); //Thread.Sleep(1); //Win32API.KeyUp(Keys.X); } //Win32API.KeyDown(Keys.Alt); //Win32API.KeyDown(Keys.F4); Win32API.KeyDown(Keys.Alt); //Win32API.KeyDown(Keys.F4); Win32API.KeyUp(Keys.F4); //Win32API.KeyUp(Keys.Alt); //Win32API.SendTwoKeyDown(Keys.Alt, Keys.F4); //SendKeys.SendWait("^s"); //发送 Ctrl + s 键 //SendKeys.SendWait("%{F4}"); // 发送 Alt + F4 键 //MessageBox.Show("文件已经保存成功!"); } }
public override bool Connect() { try { if (_externalTool.TryIntegrate == false) { _externalTool.Start(InterfaceControl.Info); Close(); return false; } ExternalToolArgumentParser argParser = new ExternalToolArgumentParser(_externalTool.ConnectionInfo); _process = new Process(); _process.StartInfo.UseShellExecute = true; _process.StartInfo.FileName = argParser.ParseArguments(_externalTool.FileName); _process.StartInfo.Arguments = argParser.ParseArguments(_externalTool.Arguments); _process.EnableRaisingEvents = true; _process.Exited += ProcessExited; _process.Start(); _process.WaitForInputIdle(Convert.ToInt32(Settings.Default.MaxPuttyWaitTime * 1000)); int startTicks = Environment.TickCount; while (_handle.ToInt32() == 0 & Environment.TickCount < startTicks + (Settings.Default.MaxPuttyWaitTime * 1000)) { _process.Refresh(); if (_process.MainWindowTitle != "Default IME") { _handle = _process.MainWindowHandle; } if (_handle.ToInt32() == 0) { Thread.Sleep(0); } } NativeMethods.SetParent(_handle, InterfaceControl.Handle); Runtime.MessageCollector.AddMessage(Messages.MessageClass.InformationMsg, Language.strIntAppStuff, true); Runtime.MessageCollector.AddMessage(Messages.MessageClass.InformationMsg, string.Format(Language.strIntAppHandle, _handle.ToString()), true); Runtime.MessageCollector.AddMessage(Messages.MessageClass.InformationMsg, string.Format(Language.strIntAppTitle, _process.MainWindowTitle), true); Runtime.MessageCollector.AddMessage(Messages.MessageClass.InformationMsg, string.Format(Language.strIntAppParentHandle, InterfaceControl.Parent.Handle.ToString()), true); Resize(this, new EventArgs()); base.Connect(); return true; } catch (Exception ex) { Runtime.MessageCollector.AddExceptionMessage(Language.strIntAppConnectionFailed, ex); return false; } }
protected override HandleRef BuildWindowCore(HandleRef hwndParent) { _hwndHost = IntPtr.Zero; _hwndHost = NativeMethods.CreateWindowEx( 0, "static", "", NativeMethods.WsChild | NativeMethods.WsVisible | NativeMethods.WsClipChildren, 0, 0, _hostWidth, _hostHeight, hwndParent.Handle, IntPtr.Zero, IntPtr.Zero, 0); // This code uses Thread.Sleep, so finish on a background thread Task.Factory.StartNew(() => { string haloExePath = App.MetroIdeStorage.MetroIdeSettings.HaloExePath; if (!File.Exists(haloExePath)) return; string haloDirectory = Path.GetDirectoryName(haloExePath); if (haloDirectory == null || !Directory.Exists(haloDirectory)) return; _haloProcess = Process.Start(new ProcessStartInfo(haloExePath) { WorkingDirectory = haloDirectory, Arguments = string.Format(@"-console -window -vidmode {0},{1},60", 800, 600), WindowStyle = ProcessWindowStyle.Minimized }); _haloProcess.WaitForInputIdle(); Thread.Sleep(2000); // remove control box int style = NativeMethods.GetWindowLong(_haloProcess.MainWindowHandle, NativeMethods.GwlStyle); style = style & ~NativeMethods.WsCaption & ~NativeMethods.WsThickframe; NativeMethods.SetWindowLong(_haloProcess.MainWindowHandle, NativeMethods.GwlStyle, style); // reveal and relocate into our window NativeMethods.SetParent(_haloProcess.MainWindowHandle, _hwndHost); NativeMethods.ShowWindow(_haloProcess.MainWindowHandle, NativeMethods.SwShow); // resize NativeMethods.SetWindowPos(_haloProcess.MainWindowHandle, IntPtr.Zero, 0, 0, 800, 600, NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate); // force video rendering const int exeOffset = 0x400000; const int wmkillHandlerOffset = exeOffset + 0x142538; var wmkillHandler = new WinMemoryByteAccess(wmkillHandlerOffset, 4); wmkillHandler.WriteBytes(0, new byte[] { 0xe9, 0x91, 0x00, 0x00 }); }); return new HandleRef(this, _hwndHost); }
public ClientMC(Process p) { process = p; process.WaitForInputIdle(); while (process.MainWindowHandle == IntPtr.Zero) { process.Refresh(); System.Threading.Thread.Sleep(5); } processHandle = WinApi.OpenProcess(WinApi.PROCESS_ALL_ACCESS, 0, (uint)process.Id); }
public override IEnumerator LoadScenes([ValueSource(nameof(GetVDBScenes))] string scenePath) { var vdbProcess = new System.Diagnostics.Process(); // Close any existing instances of the VDB and make a new one { string vdbExe = System.IO.Path.GetFullPath("Packages/com.havok.physics/Tools/VisualDebugger/HavokVisualDebugger.exe"); string vdbProcessName = System.IO.Path.GetFileNameWithoutExtension(vdbExe); List <System.Diagnostics.Process> processes = new List <System.Diagnostics.Process>(); processes.AddRange(System.Diagnostics.Process.GetProcessesByName(vdbProcessName)); foreach (var process in processes) { process.CloseMainWindow(); process.Close(); } vdbProcess.StartInfo.FileName = vdbExe; vdbProcess.StartInfo.Arguments = ""; vdbProcess.Start(); vdbProcess.WaitForInputIdle(); // How do we ensure the VDB is ready to connect? yield return(new WaitForSeconds(2)); vdbProcess.Refresh(); } var havokConfig = HavokConfiguration.Default; // Enabled VDB havokConfig.VisualDebugger.Enable = 1; yield return(SetupAndLoadScene(World.DefaultGameObjectInjectionWorld, havokConfig, scenePath)); // Disabled VDB havokConfig.VisualDebugger.Enable = 0; yield return(SetupAndLoadScene(World.DefaultGameObjectInjectionWorld, havokConfig, scenePath)); // Enabled VDB with zero Timer memory havokConfig.VisualDebugger.Enable = 1; havokConfig.VisualDebugger.TimerBytesPerThread = 0; yield return(SetupAndLoadScene(World.DefaultGameObjectInjectionWorld, havokConfig, scenePath)); // Close VDB client vdbProcess.CloseMainWindow(); vdbProcess.Close(); // Enabled VDB with no Client running. havokConfig = HavokConfiguration.Default; havokConfig.VisualDebugger.Enable = 1; yield return(SetupAndLoadScene(World.DefaultGameObjectInjectionWorld, havokConfig, scenePath)); LogAssert.NoUnexpectedReceived(); }
private static void StartIis() { try { _webHostProcess = Process.Start(GetProcessStartInfo()); _webHostProcess.WaitForInputIdle(); } catch { KillHosts(); } }
public Flexisign() { ProcessStartInfo info = new ProcessStartInfo(@"C:\Program Files\FlexiSIGN-PRO 8.1v1\Program\App.exe"); process = Process.Start(info); process.WaitForInputIdle(); Thread.Sleep(2000); do { window = AutomationElement.RootElement.FindChildByProcessId(process.Id); } while(window == null); //System.Diagnostics.Debug.WriteLine("Found the first child by process id: "+process.ProcessName); }
public MainWindow2() { InitializeComponent(); string meikPath = OperateIniFile.ReadIniData("Base", "MEIK base", "C:\\Program Files (x86)\\MEIK 5.6", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"); meikPath += "\\MEIK.exe"; if (File.Exists(meikPath)) { try { //启动外部程序 AppProc = Process.Start(meikPath); if (AppProc != null) { AppProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 //proc.WaitForExit();//等待外部程序退出后才能往下执行 AppProc.WaitForInputIdle(); /**这段代码是把其他程序的窗体嵌入到当前窗体中**/ IntPtr appWinHandle = AppProc.MainWindowHandle; IntPtr mainWinHandle = new WindowInteropHelper(this).Handle; SetParent(appWinHandle, mainWinHandle); //监视进程退出 AppProc.EnableRaisingEvents = true; //指定退出事件方法 AppProc.Exited += new EventHandler(proc_Exited); // BackButtonWindow backButtonWindow = new BackButtonWindow(); //backButtonWindow.Owner = this; //backButtonWindow.Show(); //backButtonWindow.Hide(); //windowListen.AppProc = AppProc; //windowListen.backWinHwnd = new WindowInteropHelper(backButtonWindow).Handle; //侦听MEIK程序是否打开全屏窗体 //Thread workerThread = new Thread(windowListen.Run); //workerThread.Start(); } } catch (ArgumentException ex) { this.Show(); MessageBox.Show("Failed to start MEIK software v. 5.6, Exception: " +ex.Message); } } else { this.Show(); MessageBox.Show("The file " + meikPath + "\\MEIK.exe is not exist."); } }
protected WindowInfoWithHandle LaunchSampleApplication() { var proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = @"c:\Windows\System32\notepad.exe"; proc.Start(); proc.WaitForInputIdle(); proc.Refresh(); //Debug.WriteLine(proc.MainWindowHandle); var windowInfoWithHandle = new WindowInfoWithHandle(proc.MainWindowHandle); return(windowInfoWithHandle); }
private void 打印ToolStripMenuItem_Click(object sender, EventArgs e) { //为了简化处理, 这直接将文件送到打印机打印,不是别好 //有兴趣的话可以尝试打印richtextbox的内容, 要留图和格式 if (filename == null || filename == "") { MessageBox.Show("save first,please!"); return; } System.Diagnostics.Process p = new System.Diagnostics.Process(); try { p.StartInfo.FileName = filename; p.StartInfo.WorkingDirectory = (new FileInfo(filename)).DirectoryName; p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.Verb = "Print"; p.Start(); if (!p.HasExited) { p.WaitForInputIdle(10000); int i = 1; bool running = true; while (running && i <= 20) { System.Threading.Thread.Sleep(500); if (p.HasExited) { running = false; } else { running = !p.CloseMainWindow(); } i++; } if (running && !p.HasExited) { p.Kill(); } } p.Dispose(); } catch (Exception ee) { MessageBox.Show(ee.Message); } }
private void button_Click(object sender, RoutedEventArgs e) { p = System.Diagnostics.Process.Start(ofd.FileName); //念のため待つ。 p.WaitForInputIdle(); //ウィンドウハンドルが取得できるか、 //生成したプロセスが終了するまで待ってみる。 while (p.MainWindowHandle == IntPtr.Zero && p.HasExited == false) { System.Threading.Thread.Sleep(1); p.Refresh(); } }
public void OpenFile(string fileName) { System.Diagnostics.Debug.WriteLine("opening file "+fileName+"..."); ProcessStartInfo info = new ProcessStartInfo(fileName); process = Process.Start(info); process.WaitForInputIdle(); Thread.Sleep(2000); do { //TODO: handle if hang or passing 5 sec window = AutomationElement.RootElement.FindChildByProcessId(process.Id); } while(window == null); System.Diagnostics.Debug.WriteLine("Found the first child by process id: "+process.ProcessName); }
static void Main(string[] args) { Console.TreatControlCAsInput = true; int check_i = 0; int win_number = 0; string kkk = ""; while (true) { //該Soft Ctrl+C 關閉 cmd禁止 ConsoleKeyInfo key2 = Console.ReadKey(true); win_number = (key2.Key == ConsoleKey.NumPad8) ? check_i += 1 : check_i -= check_i; //start write txt //Console.WriteLine(key.Key); kkk += key2.Key.ToString(); if (win_number == 8) { break; } } /*if (kkk.Length > 0) Console.WriteLine(kkk); { }*/ var p = new Process { StartInfo = { FileName = "notepad.exe" } }; p.Start(); try { List<Key> keys = kkk.Select(c => new Key(c)).ToList(); var procId = p.Id; p.WaitForInputIdle(); foreach (var key in keys) { key.PressForeground(p.MainWindowHandle); } } catch (InvalidOperationException) { } }
private void buttonStart_Click(object sender, EventArgs e) { string argument = Application.StartupPath + "\\myfile" + fileIndex + ".txt"; if (File.Exists(argument) == false) { File.CreateText(argument); } ProcessStartInfo ps = new ProcessStartInfo(fileName, argument); ps.WindowStyle = ProcessWindowStyle.Normal; fileIndex++; Process p = new Process(); p.StartInfo = ps; p.Start(); p.WaitForInputIdle(); RefreshListView(); }
public void ProcessStart() { using (Process p = new Process()) { ProcessStartInfo info = new ProcessStartInfo(); info.WorkingDirectory = WorkingDirectory; info.FileName = FileName; info.Arguments = Arguments; info.WindowStyle = WindowStyle; p.StartInfo = info; p.Start(); if (IsWaitForInputIdle) p.WaitForInputIdle(); if (!p.HasExited) p.WaitForExit(); } }
//--------------------------------------------------------------------- void Test1 () { ProcessStartInfo psi1 = new ProcessStartInfo("notepad"); Process proc1 = new Process() { StartInfo = psi1 }; proc1.Start(); proc1.WaitForInputIdle(); IntPtr handle1 = proc1.MainWindowHandle; uint exStyle1 = WinAPI.GetWindowLongPtr(handle1, -20); //WinAPI.SetWindowLongPtr(new HandleRef(this, handle1), -20, new UIntPtr(exStyle1 | WinAPI.WS_EX.LAYERED)); //WinAPI.SetLayeredWindowAttributes(handle1, 0, 255 * 80 / 100, 2); ShadowCanvas scanvas1 = new ShadowCanvas(); scanvas1.Init(handle1, this, EmbeddingOptions.DontClip); scanvas1.Embeddable = true; Grid1.Children.Add(scanvas1); scanvas1.Grab(); _canvases.Add(scanvas1); _processes.Add(proc1); }
private void InvokeDialogOk(Process process, AutomationElement window, string dialogClass, string okName) { process.WaitForInputIdle(); AutomationElement dialog = window.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, dialogClass)); while(dialog == null) { Thread.Sleep(16); dialog = window.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, dialogClass)); } AutomationElement button = dialog.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, okName)); object invoke; if (button.TryGetCurrentPattern(InvokePattern.Pattern, out invoke)) { ((InvokePattern)invoke).Invoke(); } }
public void OpenSelectedItemInApp() { appProc = new Process { StartInfo = new ProcessStartInfo { FileName = appPath, Arguments = args + " \"" + filePath + "\"", UseShellExecute = true, CreateNoWindow = false } }; appProc.Start(); appProc.WaitForInputIdle(); }
private bool Uninstall(int ind) { string args; System.Diagnostics.Process process = new System.Diagnostics.Process(); ProcessStartInfo info = new ProcessStartInfo(); string uninstallValue = myCurrentList[ind][11]; if ((uninstallValue.Contains("MsiExec.exe")) && (!string.IsNullOrEmpty(uninstallValue))) { args = "/x{" + uninstallValue.Split("/".ToCharArray())[1].Split("I{".ToCharArray())[2]; } else { args = string.Empty; } try { if (!string.IsNullOrEmpty(args)) { info.FileName = uninstallValue.Split("/".ToCharArray())[0]; } else { info.FileName = uninstallValue; info.Arguments = args; } info.RedirectStandardError = false; info.RedirectStandardOutput = false; info.RedirectStandardInput = false; info.UseShellExecute = false; info.CreateNoWindow = true; process.EnableRaisingEvents = true; process.StartInfo = info; process.Start(); process.WaitForInputIdle(); process.WaitForExit(); return(true); } catch (Exception ex) { MessageBox.Show(ex.Message); return(false); } }
//------------------------------------------- // process をスタート //------------------------------------------- public static bool Start(Dictionary <string, string> iParams) { try { // 現在、動作しているプロセスをすべてコロ助 Kill(); // プロセスをスタートさせる // プロファイルのパス //string profile_path = Path.GetTempPath() + "nicovideo_fme.xml"; string profile_path = Properties.Settings.Default.fmle_profile_path + "\\" + Properties.Settings.Default.fmle_default_profile; // FlashMediaEncoderのパス string path = Properties.Settings.Default.fmle_path.Replace("FMLECmd", "FlashMediaLiveEncoder"); // プロファイル作成 if (!FMLE.MakeProfile(profile_path, iParams)) { mFMEStarted = false; return(false); } // FMLECmd起動 string args = " /g /p \"" + profile_path + "\""; mFMEprocess = System.Diagnostics.Process.Start(path, args); // ウインドウハンドルが生成されるまで待つ mFMEprocess.WaitForInputIdle(); // 立ち上がるのを待つ using (Bouyomi bm = new Bouyomi()) { bm.Talk("えふえむいー起動中です"); } System.Threading.Thread.Sleep(8000); return(PushStart()); } catch (Exception e) { Utils.WriteLog(e.ToString()); return(false); } }
IEnumerator connect() { System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); info.CreateNoWindow = false; info.FileName = "python.exe"; info.Arguments = "C:\\Users\\sloov\\Desktop\\mnist\\mnist_user.py"; info.UseShellExecute = false; System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = info; p.Start(); p.WaitForInputIdle(); yield return(new WaitForSeconds(2)); tcp = new TcpClient(host, port); if (tcp.Connected) { connected = true; } }
private void OpenText() { //启动notepad.exe 记事本程序,并在d:\下创建 或 打开 text_test.txt文件 System.Diagnostics.Process txt = System.Diagnostics.Process.Start(@"SRManager.exe"); txt.StartInfo.WindowStyle = ProcessWindowStyle.Normal; //等待一秒,以便目标程序notepad.exe输入状态就绪 txt.WaitForInputIdle(200); /*IntPtr hwndCalc = FindWindow("SRManager", null); //查找计算器的句柄*/ IntPtr hwndCalc = txt.Handle; const uint BM_CLICK = 0xF5; //鼠标点击的消息,对于各种消息的数值,大家还是得去API手册 if (hwndCalc != IntPtr.Zero) { IntPtr hwndThree = FindWindowEx(hwndCalc, 0, "CButton", null); //获取按钮3 的句柄 IntPtr hwndPlus = FindWindowEx(hwndCalc, 0, null, "+"); //获取按钮 + 的句柄 // IntPtr hwndTwo = FindWindowEx(hwndCalc, 0, null, "2"); //获取按钮2 的句柄 // IntPtr hwndEqual = FindWindowEx(hwndCalc, 0, null, "="); //获取按钮= 的句柄 SetForegroundWindow(hwndCalc); //将计算器设为当前活动窗口 /*System.Threading.Thread.Sleep(2000); //暂停2秒让你看到效果*/ /*SendMessage(hwndThree, BM_CLICK, 0, 0);*/ } //如果目标程序 notepad.exe 没有停止响应,则继续 if (txt.Responding) { //开始写入内容 SendKeys.SendWait("-----下面的内容是外部程序自动写入-----\r\n"); //SendKeys.SendWait(this.textBox1.Text); //将文本框内的内容写入 SendKeys.SendWait("{Enter}{Enter}"); //写入2个回车 SendKeys.SendWait("文档创建时间:"); //SendKeys.SendWait("{F5}"); //发送F5按键 SendKeys.SendWait("{Enter}"); //发送回车键 SendKeys.SendWait("^s"); //发送 Ctrl + s 键 //SendKeys.SendWait("%{F4}"); // 发送 Alt + F4 键 // MessageBox.Show("文件已经保存成功!"); } }
public void StartTask() { KillOtherTask(); Task = Process.Start(Path); Task.WaitForInputIdle(); for (int i = 0; Handle == IntPtr.Zero && i < 50; i++) { Handle = Task.MainWindowHandle; Thread.Sleep(100); } SetParent(Handle, Panel.Handle); SetWindowLong(Handle, GWL_STYLE, (int)(WS_VISIBLE + (WS_MAXIMIZE | WS_BORDER))); MoveWindow(Handle, 0, 0, Panel.Width, Panel.Height, true); Panel.Resize += new EventHandler(delegate(object sender, EventArgs e) { MoveWindow(Handle, 0, 0, Panel.Width, Panel.Height, true); }); }
public void Open(string exePath, string name, string args) { // Wait for process to be created and enter idle condition ProcessStartInfo info = new ProcessStartInfo(string.Format("{0}\\{1}", exePath, name), args); info.WorkingDirectory = exePath; info.WindowStyle = ProcessWindowStyle.Minimized; process = Process.Start(info); process.WaitForInputIdle(); // Change process to son of this Thread.Sleep(300); WinAPI.SetParent(process.MainWindowHandle, this.Handle); Int32 wndStyle = WinAPI.GetWindowLong(process.MainWindowHandle, WinAPI.GWL_STYLE); wndStyle &= ~WinAPI.WS_BORDER; wndStyle &= ~WinAPI.WS_THICKFRAME; WinAPI.SetWindowLong(process.MainWindowHandle, WinAPI.GWL_STYLE, wndStyle); }
private static Int32 LaunchNotepadAndGetPid() { Process proc; Int32 pid = 0; proc = new Process(); proc.StartInfo.FileName = "notepad.exe"; if (proc.Start() != false) { proc.WaitForInputIdle(); try { pid = proc.Id; } catch (Exception) { pid = 0; } } return pid; }
private void InvokeMenuItem(Process process, AutomationElement window, string menu, string menuItem) { AutomationElement menuElement = window.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, menu)); object menuExpand; if (menuElement.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out menuExpand)) { ((ExpandCollapsePattern)menuExpand).Expand(); process.WaitForInputIdle(); AutomationElement menuItemElement = menuElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, menuItem)); while (menuItemElement == null) { Thread.Sleep(16); menuItemElement = menuElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, menuItem)); } object menuItemInvoke; if (menuItemElement.TryGetCurrentPattern(InvokePattern.Pattern, out menuItemInvoke)) { ((InvokePattern)menuItemInvoke).Invoke(); } } }
/// <summary> /// 打开微课播放器 /// </summary> /// <param name="exportPath">导出路径</param> /// <param name="fileName">播放文件名</param> public void OpenWeiKePlayer(string exportPath, string fileName) { //"WeiKePlayer_Data/StreamingAssets/" if (File.Exists(exportPath + fileName + ".vsl")) { foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("WeiKePlayer")) { pro.Kill(); } //exportPath + DirectName+".vsl" String path = Vesal_DirFiles.get_dir_from_full_path(Application.dataPath) + "WeiKePlayer_Data/StreamingAssets/WeiKePlayer/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } BackUpVsl(path); try { File.Copy(exportPath + fileName + ".vsl", path + fileName + ".vsl"); } catch (Exception e) { Debug.Log(e.Message); } string exePath = Vesal_DirFiles.get_dir_from_full_path(Application.dataPath) + "WeiKePlayer.exe"; Debug.Log(exePath); if (File.Exists(exePath)) { System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo(exePath); ps.Arguments = exportPath + fileName + ".vsl"; System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = ps; p.Start(); p.WaitForInputIdle(); } } }
public bool Calc() { if (c == null) { try { c = System.Diagnostics.Process.Start("Calc.exe"); c.WaitForInputIdle(); IntPtr h = c.MainWindowHandle; SetForegroundWindow(h); return(true); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } } return(false); }
private void CalculatorBtn_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process calc = System.Diagnostics.Process.Start("calc.exe"); calc.WaitForInputIdle(); }
public bool AddSSH(string hostIN, string userIN, string passIN, string portIN) { host = hostIN; pass = passIN; port = portIN; user = userIN; try { pt1 = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = "pt.exe"; startInfo.Arguments = "-ssh " + user + "@" + host + " " + port + " -pw " + pass + " -X -C"; startInfo.WindowStyle = ProcessWindowStyle.Minimized; pt1.StartInfo = startInfo; pt1.Start(); pt1.WaitForInputIdle(); SetParent(pt1.MainWindowHandle, cliForm.cliConsole1.Handle); Utilities.HideMinimizeAndMaximizeButtons(pt1.MainWindowHandle); MoveWindow(pt1.MainWindowHandle, -8, -30, cliForm.cliConsole1.Width + 15, cliForm.cliConsole1.Height + 40, true); pt2 = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo2 = new System.Diagnostics.ProcessStartInfo(); startInfo2.FileName = "pt.exe"; startInfo2.Arguments = "-ssh " + user + "@" + host + " " + port + " -pw " + pass + " -X -C"; startInfo2.WindowStyle = ProcessWindowStyle.Minimized; pt2.StartInfo = startInfo2; // pt2.StartInfo.CreateNoWindow = true; // pt2.StartInfo.UseShellExecute = false; pt2.Start(); pt2.WaitForInputIdle(); SetParent(pt2.MainWindowHandle, cliForm.cliConsole2.Handle); Utilities.HideMinimizeAndMaximizeButtons(pt2.MainWindowHandle); MoveWindow(pt2.MainWindowHandle, -8, -30, cliForm.cliConsole2.Width + 15, cliForm.cliConsole2.Height + 40, true); pt3 = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo3 = new System.Diagnostics.ProcessStartInfo(); startInfo3.FileName = "pt.exe"; startInfo3.Arguments = "-ssh " + user + "@" + host + " " + port + " -pw " + pass + " -X -C"; startInfo3.WindowStyle = ProcessWindowStyle.Minimized; pt3.StartInfo = startInfo3; pt3.Start(); pt3.WaitForInputIdle(); SetParent(pt3.MainWindowHandle, cliForm.cliConsole3.Handle); Utilities.HideMinimizeAndMaximizeButtons(pt3.MainWindowHandle); MoveWindow(pt3.MainWindowHandle, -8, -30, cliForm.cliConsole3.Width + 15, cliForm.cliConsole3.Height + 40, true); return(true); } catch (Exception exp) { MessageBox.Show("Error : " + exp.Message); return(false); } }
public void loadDesigner(string fileName) { Project prj = HelperFunctions.GetSelectedQtProject(Connect._applicationObject); string qtVersion = null; QtVersionManager vm = QtVersionManager.The(); if (prj != null) { qtVersion = vm.GetProjectQtVersion(prj); } else { prj = HelperFunctions.GetSelectedProject(Connect._applicationObject); if (prj != null && HelperFunctions.IsQMakeProject(prj)) { string qmakeQtDir = HelperFunctions.GetQtDirFromQMakeProject(prj); qtVersion = vm.GetQtVersionFromInstallDir(qmakeQtDir); } } string qtDir = HelperFunctions.FindQtDirWithTools("designer", qtVersion); if (qtDir == null || qtDir.Length == 0) { MessageBox.Show(SR.GetString("NoDefaultQtVersionError"), Resources.msgBoxCaption); return; } try { if (!designerDict.ContainsKey(qtDir) || designerDict[qtDir].process.HasExited) { string workingDir, formFile; if (fileName == null) { formFile = ""; workingDir = (prj == null) ? null : Path.GetDirectoryName(prj.FullName); } else { formFile = fileName; workingDir = Path.GetDirectoryName(fileName); if (!formFile.StartsWith("\"")) { formFile = "\"" + formFile; } if (!formFile.EndsWith("\"")) { formFile += "\""; } } string launchCMD = "-server " + formFile; System.Diagnostics.Process tmp = getQtApplicationProcess("designer", launchCMD, workingDir, qtDir); tmp.StartInfo.UseShellExecute = false; tmp.StartInfo.RedirectStandardOutput = true; tmp.OutputDataReceived += new DataReceivedEventHandler(designerOutputHandler); tmp.Start(); tmp.BeginOutputReadLine(); try { portFound.WaitOne(5000, false); } catch (Exception e) { MessageBox.Show(e.Message); } tmp.WaitForInputIdle(); DesignerData data; data.process = tmp; data.port = designerPort; portFound.Reset(); designerDict[qtDir] = data; } else if (fileName != null) { try { TcpClient c = new TcpClient("127.0.0.1", designerDict[qtDir].port); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); byte[] bArray = enc.GetBytes(fileName + "\n"); Stream stream = c.GetStream(); stream.Write(bArray, 0, bArray.Length); c.Close(); stream.Close(); } catch { Messages.DisplayErrorMessage(SR.GetString("DesignerAddError")); } } } catch { MessageBox.Show(SR.GetString("QtAppNotFoundErrorMessage", "Qt Designer"), SR.GetString("QtAppNotFoundErrorTitle", "Designer")); return; } try { if ((int)designerDict[qtDir].process.MainWindowHandle == 0) { System.Diagnostics.Process prc = System.Diagnostics.Process.GetProcessById(designerDict[qtDir].process.Id); if ((int)prc.MainWindowHandle != 0) { DesignerData data; data.process = prc; data.port = designerDict[qtDir].port; designerDict[qtDir] = data; } } SwitchToThisWindow(designerDict[qtDir].process.MainWindowHandle, true); } catch { // silent } }
bool InternalOpen() { string bookname; string topicList = null; string fileName = (String.IsNullOrEmpty(System.IO.Path.GetDirectoryName(m_settings.BookName))) ? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + m_settings.BookName : m_settings.BookName; // открываем уже существующий документ и лист if (!ExcelDDEManager.Instance.Open(this, Command.DDEName(System.IO.Path.GetFileName(fileName), m_settings.SheetName))) { // что-то не создано... открываем системный dde if (!ExcelDDEManager.Instance.Open()) { // нужно запустить сам excel System.Diagnostics.Process p = System.Diagnostics.Process.Start("excel.exe"); p.WaitForInputIdle(); // ну вообще с dde траблы if (!ExcelDDEManager.Instance.Open()) { return(false); } } // открыть имеющийся файл if (System.IO.File.Exists(fileName)) { ExcelDDEManager.Instance.ExecuteMacro(String.Concat("[OPEN(\"", fileName, "\")]\0")); int wait = 2; while (wait > 0) { // попытаемся переоткрыть лист if (ExcelDDEManager.Instance.Open(this, Command.DDEName(System.IO.Path.GetFileName(fileName), m_settings.SheetName))) { m_settings.BookName = fileName; ExcelDDEManager.Instance.ExecuteMacroAsync(this, String.Concat("[WORKBOOK.ACTIVATE(\"", m_settings.SheetName, "\")]\0")); return(true); } Thread.Sleep(1000);// дадим книге загрузится... wait--; } // создаем новый лист ExcelDDEManager.Instance.ExecuteMacro("[WORKBOOK.INSERT(1)]\0"); } else { // новая книга ExcelDDEManager.Instance.ExecuteMacro("[NEW(1)]\0"); // переименовываем ExcelDDEManager.Instance.ExecuteMacro(String.Concat("[SAVE.AS(\"", fileName, "\")]\0")); } // находим топики загруженной книги topicList = null; Stopwatch startWaiting = Stopwatch.StartNew(); while (String.IsNullOrEmpty(topicList)) { // если excel выкинул диалог, список пустой или нулл ExcelDDEManager.Instance.Request("Topics\0", out topicList); if (startWaiting.ElapsedMilliseconds > AppConfig.Common.WaitExcelTimeout) { // что-то пошло не так... if (XtraMessageBox.Show(MainForm.Instance.activeControl, "Истекло время ожидания ответа от сервера Excel.\r\nПродолжить ожидание?", "ВНИМАНИЕ", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) { return(false); } startWaiting = Stopwatch.StartNew(); } } //if (topicList != null) { bookname = System.IO.Path.GetFileName(fileName); string[] topics = topicList.Split('\t') // нужны топики только выбранной книги: [книга]лист .Where(t => t.Contains(bookname)) .ToArray(); // переименовываем последний лист в списке if (topics.Length > 0) // в книге хотя бы один лист { string[] tname = topics[topics.Length - 1].Split(']'); if (tname.Length == 2) // в кни { bookname = tname[0].Substring(1); // имя книги может не совпадать с фактическим // переименовываем последний лист в списке ExcelDDEManager.Instance.ExecuteMacro(String.Concat("[WORKBOOK.NAME(\"", tname[1], "\",\"", m_settings.SheetName, "\")]\0")); } } } // попытаемся переоткрыть лист if (ExcelDDEManager.Instance.Open(this, Command.DDEName(bookname, m_settings.SheetName))) { m_settings.BookName = System.IO.Path.GetDirectoryName(fileName) + "\\" + bookname; ExcelDDEManager.Instance.ExecuteMacroAsync(this, String.Concat("[WORKBOOK.ACTIVATE(\"", m_settings.SheetName, "\")]\0")); return(true); } return(false); } return(true); }
public void RunGame(string cmdArguments, int systemId) { /* * // check mednafen.exe instruction set * InstructionSet medInst = InstructionSetDetector.GetExeInstructionSet(BuildMednafenPath(MednafenFolder)); * // get operating system type * InstructionSet osInst = InstructionSetDetector.GetOperatingSystemInstructionSet(); * * if (osInst == InstructionSet.x86) * { * if (medInst == InstructionSet.x64) * { * MessageBox.Show("You are targetting a 64-bit version of Mednafen on a 32-bit operating system. This will not work.\n\nPlease target a 32-bit (x86) version of Mednafen", "Warning", MessageBoxButton.OK, MessageBoxImage.Exclamation); * return; * } * * if (systemId == 13 && medInst == InstructionSet.x86) * { * MessageBox.Show("You are trying to emulate a Sega Saturn game using a 32-bit Mednafen build on a 32-bit operating system. This will not work.\n\nYou are unable to emulate Saturn games on this machine", "Warning", MessageBoxButton.OK, MessageBoxImage.Exclamation); * return; * } * * if (systemId == 13) * { * MessageBox.Show("You are trying to emulate a Sega Saturn game using a 32-bit operating system. This will not work.\n\nYou are unable to emulate Saturn games on this machine", "Warning", MessageBoxButton.OK, MessageBoxImage.Exclamation); * return; * } * } * * if (osInst == InstructionSet.x64) * { * if (systemId == 13 && medInst == InstructionSet.x86) * { * MessageBox.Show("You are trying to emulate a Sega Saturn game using a 32-bit Mednafen build. This will not work.\n\nPlease target a 64-bit (x64) version of Mednafen", "Warning", MessageBoxButton.OK, MessageBoxImage.Exclamation); * return; * } * } * */ int procId; bool rememberWinPos = GlobalSettings.GetGlobals().rememberSysWinPositions.Value; using (System.Diagnostics.Process gProcess = new System.Diagnostics.Process()) { gProcess.StartInfo.UseShellExecute = true; gProcess.StartInfo.RedirectStandardOutput = false; gProcess.StartInfo.WorkingDirectory = "\"" + MednafenFolder + "\""; gProcess.StartInfo.FileName = "\"" + BuildMednafenPath(MednafenFolder) + "\""; gProcess.StartInfo.CreateNoWindow = false; // Build command line config arguments gProcess.StartInfo.Arguments = cmdArguments; gProcess.Start(); gProcess.WaitForInputIdle(); procId = gProcess.Id; IntPtr hwnd = new IntPtr(); // set windows position System.Drawing.Point pnt = new System.Drawing.Point(); // get process window handle try { hwnd = gProcess.MainWindowHandle; if (rememberWinPos == true) { // get windows position from database pnt = GlobalSettings.GetWindowPosBySystem(systemId); // set windows position HwndInterface.SetHwndPos(hwnd, pnt.X, pnt.Y); } bool isClosed = false; while (isClosed == false) { try { // get process id Process p = Process.GetProcessById(procId); if (rememberWinPos == true) { // get window top left x y coords pnt = HwndInterface.GetHwndPos(hwnd); } } catch { isClosed = true; } Thread.Sleep(1000); } if (rememberWinPos == true) { // save coords to database GlobalSettings.SaveWindowPosBySystem(systemId, pnt); } } catch { // catch exception if mednafen doesnt launch correctly return; } } }
public void RunGame(string cmdArguments, int systemId) { int procId; bool rememberWinPos = GlobalSettings.GetGlobals().rememberSysWinPositions.Value; using (System.Diagnostics.Process gProcess = new System.Diagnostics.Process()) { gProcess.StartInfo.UseShellExecute = true; gProcess.StartInfo.RedirectStandardOutput = false; gProcess.StartInfo.WorkingDirectory = "\"" + MednafenFolder + "\""; gProcess.StartInfo.FileName = "\"" + BuildMednafenPath(MednafenFolder) + "\""; gProcess.StartInfo.CreateNoWindow = false; // Build command line config arguments gProcess.StartInfo.Arguments = cmdArguments; gProcess.Start(); gProcess.WaitForInputIdle(); procId = gProcess.Id; // get process window handle IntPtr hwnd = gProcess.MainWindowHandle; // set windows position System.Drawing.Point pnt = new System.Drawing.Point(); if (rememberWinPos == true) { // get windows position from database pnt = GlobalSettings.GetWindowPosBySystem(systemId); // set windows position HwndInterface.SetHwndPos(hwnd, pnt.X, pnt.Y); } bool isClosed = false; while (isClosed == false) { try { // get process id Process p = Process.GetProcessById(procId); if (rememberWinPos == true) { // get window top left x y coords pnt = HwndInterface.GetHwndPos(hwnd); } } catch { isClosed = true; } Thread.Sleep(1000); } if (rememberWinPos == true) { // save coords to database GlobalSettings.SaveWindowPosBySystem(systemId, pnt); } } }
private void OnGUI() { csharpCmd = "\n --proto_path=" + setting.ProtoFilesPath + "\n"; csharpCmd += " --csharp_out=" + setting.CSharpOutput + "\n"; foreach (var file in protoFiles) { var containsSynx = File.ReadAllText(file).Contains("proto3"); if (setting.version == ProtoVersion.Proto2 && containsSynx || setting.version == ProtoVersion.Proto3 && !containsSynx) { continue; } csharpCmd += " " + file + "\n"; } luaCmd = "\n -I=" + setting.ProtoFilesPath.Replace("\\", "/") + "\n"; luaCmd += " --lua_out=" + setting.LuaOutput.Replace("\\", "/") + "\n"; luaCmd += " --plugin=protoc-gen-lua=protoc-gen-lua.bat"; foreach (var file in protoFiles) { if (File.ReadAllText(file).Contains("proto3")) { continue; } luaCmd += " " + file.Replace("\\", "/") + "\n"; } if (GUILayout.Button("Generate code", GUILayout.ExpandWidth(true), GUILayout.Height(30))) { if (setting.CSharp && setting.version == ProtoVersion.Proto3) { var csharpStartInfo = new System.Diagnostics.ProcessStartInfo(); csharpStartInfo.WorkingDirectory = @"c:\"; csharpStartInfo.FileName = setting.CSharpGenerator; csharpStartInfo.CreateNoWindow = false; csharpStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; csharpStartInfo.ErrorDialog = true; csharpStartInfo.Arguments = csharpCmd; var csharpProcess = System.Diagnostics.Process.Start(csharpStartInfo); csharpProcess.WaitForInputIdle(); } if (setting.Lua && setting.version == ProtoVersion.Proto2) { var luaStartInfo = new System.Diagnostics.ProcessStartInfo(); luaStartInfo.CreateNoWindow = false; luaStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; luaStartInfo.ErrorDialog = true; luaStartInfo.FileName = setting.LuaGenerator; var strs = setting.LuaGenerator.Split('\\'); var genLength = strs[strs.Length - 1].Length; luaStartInfo.WorkingDirectory = setting.LuaGenerator.Remove(setting.LuaGenerator.Length - genLength, genLength); luaStartInfo.Arguments = luaCmd; System.Diagnostics.Process luaProcess = System.Diagnostics.Process.Start(luaStartInfo); luaProcess.WaitForInputIdle(); } AssetDatabase.Refresh(); } csharpFold = EditorGUILayout.Foldout(csharpFold, "C# generate option"); if (csharpFold) { var csharpRect = EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("C# generate tool", GUILayout.Width(120))) { string path = EditorUtility.OpenFilePanel("Select Tool ProtoGen.exe in ProtoBuf", "", ""); setting.CSharpGenerator = path.Replace("/", "\\"); Debug.Log(setting.CSharpGenerator); } setting.CSharpGenerator = EditorGUILayout.TextField(new GUIContent(""), setting.CSharpGenerator); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("C# output", GUILayout.Width(120))) { string path = EditorUtility.OpenFolderPanel("Select C# Output Dir", "", ""); setting.CSharpOutput = path.Replace("/", "\\"); } setting.CSharpOutput = EditorGUILayout.TextField(new GUIContent(""), setting.CSharpOutput); EditorGUILayout.EndHorizontal(); setting.CSharp = EditorGUILayout.Toggle("Generate", setting.CSharp); if (setting.CSharp) { EditorGUILayout.PrefixLabel("CMD Preview"); EditorGUILayout.TextArea(setting.CSharpGenerator + csharpCmd); } EditorGUILayout.EndVertical(); EditorGUI.DrawRect(csharpRect, Color.cyan / 3f); if (setting.CSharp && setting.version == ProtoVersion.Proto2) { EditorGUILayout.HelpBox("C# generator does not support proto2 !", MessageType.Warning, true); } } luaFold = EditorGUILayout.Foldout(luaFold, "Lua generate option"); if (luaFold) { var luaRect = EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("Lua generate tool", GUILayout.Width(120))) { string path = EditorUtility.OpenFilePanel("Select Lua tool", "", ""); setting.LuaGenerator = path.Replace("/", "\\"); } setting.LuaGenerator = EditorGUILayout.TextField(new GUIContent(""), setting.LuaGenerator); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("Lua output", GUILayout.Width(120))) { string path = EditorUtility.OpenFolderPanel("Select lua output dir", "", ""); setting.LuaOutput = path.Replace("/", "\\"); } setting.LuaOutput = EditorGUILayout.TextField(new GUIContent(""), setting.LuaOutput); EditorGUILayout.EndHorizontal(); setting.Lua = EditorGUILayout.Toggle("Generate", setting.Lua); if (setting.Lua) { EditorGUILayout.PrefixLabel("CMD Preview"); EditorGUILayout.TextArea(setting.LuaGenerator + luaCmd); } EditorGUILayout.EndVertical(); EditorGUI.DrawRect(luaRect, Color.blue / 3f); if (setting.Lua && setting.version == ProtoVersion.Proto3 && setting.Lua) { EditorGUILayout.HelpBox("Lua generator does not support proto3 !", MessageType.Warning, true); } } GUILayout.Space(25f); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); if (GUILayout.Button("Proto Files Dir", GUILayout.Width(120))) { string path = EditorUtility.OpenFolderPanel("Select Proto Files Dir", "", ""); if (!string.IsNullOrEmpty(path)) { protoFiles = Directory.GetFiles(path); setting.ProtoFilesPath = path.Replace("/", "\\"); } OnEnable(); } setting.ProtoFilesPath = EditorGUILayout.TextField("", setting.ProtoFilesPath); EditorGUILayout.EndHorizontal(); setting.version = (ProtoVersion)EditorGUILayout.EnumPopup("Version", setting.version); encodingNameIndex = EditorGUILayout.Popup("Encoding", encodingNameIndex, encodingNames); EditorGUILayout.Space(); scrollPos = EditorGUILayout.BeginScrollView(scrollPos); EditorGUILayout.LabelField("Protobuf Files"); for (int i = 0; i < protoFiles.Length; i++) { var fileName = protoFiles[i]; if (protoFileFolds.Length > i) { if (protoFileFolds[i] = EditorGUILayout.Foldout(protoFileFolds[i], (i + 1).ToString() + " : " + fileName)) { if (!File.Exists(fileName)) { continue; } var text = File.ReadAllText(fileName, Encoding.GetEncoding(encodingNames[encodingNameIndex])); EditorGUILayout.TextArea(text); } } EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); } EditorGUILayout.EndScrollView(); GUILayout.Space(15f); EditorPrefs.SetString(protoSettingKey, JsonUtility.ToJson(setting)); }