Best FlaUI code snippet using FlaUI.Core.Application.FindProcess
Application.cs
Source:Application.cs
...61 /// </summary>62 /// <param name="processId">The process id.</param>63 /// <param name="isStoreApp">Flag to define if it's a store app or not.</param>64 public Application(int processId, bool isStoreApp = false)65 : this(FindProcess(processId), isStoreApp)66 {67 }6869 /// <summary>70 /// Creates an application object with the given process.71 /// </summary>72 /// <param name="process">The process.</param>73 /// <param name="isStoreApp">Flag to define if it's a store app or not.</param>74 public Application(Process process, bool isStoreApp = false)75 {76 _process = process ?? throw new ArgumentNullException(nameof(process));77 IsStoreApp = isStoreApp;78 }7980 /// <summary>81 /// Closes the application. Force-closes it after a small timeout.82 /// </summary>83 /// <returns>Returns true if the application was closed normally and false if it was force-closed.</returns>84 public bool Close()85 {86 Logger.Default.Debug("Closing application");87 if (_disposed || _process.HasExited)88 {89 return true;90 }91 _process.CloseMainWindow();92 if (IsStoreApp)93 {94 return true;95 }96 _process.WaitForExit(5000);97 if (!_process.HasExited)98 {99 Logger.Default.Info("Application failed to exit, killing process");100 _process.Kill();101 _process.WaitForExit(5000);102 return false;103 }104 return true;105 }106107 /// <summary>108 /// Kills the applications and waits until it is closed.109 /// </summary>110 public void Kill()111 {112 try113 {114 if (_process.HasExited)115 {116 return;117 }118 _process.Kill();119 _process.WaitForExit();120 }121 catch122 {123 // NOOP124 }125 }126127 public void Dispose()128 {129 Dispose(true);130 GC.SuppressFinalize(this);131 }132133 protected virtual void Dispose(bool disposing)134 {135 if (_disposed)136 {137 return;138 }139 if (disposing)140 {141 _process?.Dispose();142 }143 _disposed = true;144 }145146 public static Application Attach(int processId)147 {148 return Attach(FindProcess(processId));149 }150151 public static Application Attach(Process process)152 {153 Logger.Default.Debug($"[Attaching to process:{process.Id}] [Process name:{process.ProcessName}] [Process full path:{process.MainModule.FileName}]");154 return new Application(process);155 }156157 public static Application Attach(string executable, int index = 0)158 {159 var processes = FindProcess(executable);160 if (processes.Length > index)161 {162 return Attach(processes[index]);163 }164 throw new Exception("Unable to find process with name: " + executable);165 }166167 public static Application AttachOrLaunch(ProcessStartInfo processStartInfo)168 {169 var processes = FindProcess(processStartInfo.FileName);170 return processes.Length == 0 ? Launch(processStartInfo) : Attach(processes[0]);171 }172173 public static Application Launch(string executable)174 {175 var processStartInfo = new ProcessStartInfo(executable);176 return Launch(processStartInfo);177 }178179 public static Application Launch(ProcessStartInfo processStartInfo)180 {181 if (String.IsNullOrEmpty(processStartInfo.WorkingDirectory))182 {183 processStartInfo.WorkingDirectory = ".";184 }185186 Logger.Default.Debug("[Launching process:{0}] [Working directory:{1}] [Process full path:{2}] [Current Directory:{3}]",187 processStartInfo.FileName,188 new DirectoryInfo(processStartInfo.WorkingDirectory).FullName,189 new FileInfo(processStartInfo.FileName).FullName,190 Environment.CurrentDirectory);191192 Process process;193 try194 {195 process = Process.Start(processStartInfo);196 }197 catch (Win32Exception ex)198 {199 var error = String.Format(200 "[Failed Launching process:{0}] [Working directory:{1}] [Process full path:{2}] [Current Directory:{3}]",201 processStartInfo.FileName,202 new DirectoryInfo(processStartInfo.WorkingDirectory).FullName,203 new FileInfo(processStartInfo.FileName).FullName,204 Environment.CurrentDirectory);205 Logger.Default.Error(error, ex);206 throw;207 }208209 return new Application(process);210 }211212 public static Application LaunchStoreApp(string appUserModelId, string arguments = null)213 {214 var process = WindowsStoreAppLauncher.Launch(appUserModelId, arguments);215 return new Application(process, true);216 }217218 /// <summary>219 /// Waits as long as the application is busy.220 /// </summary>221 /// <param name="waitTimeout">An optional timeout. If null is passed, the timeout is infinite.</param>222 /// <returns>True if the application is idle, false otherwise.</returns>223 public bool WaitWhileBusy(TimeSpan? waitTimeout = null)224 {225 var waitTime = (waitTimeout ?? TimeSpan.FromMilliseconds(-1)).TotalMilliseconds;226 return _process.WaitForInputIdle((int)waitTime);227 }228229 /// <summary>230 /// Waits until the main handle is set.231 /// </summary>232 /// <param name="waitTimeout">An optional timeout. If null is passed, the timeout is infinite.</param>233 /// <returns>True a main window handle was found, false otherwise.</returns>234 public bool WaitWhileMainHandleIsMissing(TimeSpan? waitTimeout = null)235 {236 var waitTime = waitTimeout ?? TimeSpan.FromMilliseconds(-1);237 return Retry.WhileTrue(() =>238 {239 _process.Refresh();240 return _process.MainWindowHandle == IntPtr.Zero;241 }, waitTime, TimeSpan.FromMilliseconds(50)).Result;242 }243244 /// <summary>245 /// Gets the main window of the application's process.246 /// </summary>247 /// <param name="automation">The automation object to use.</param>248 /// <param name="waitTimeout">An optional timeout. If null is passed, the timeout is infinite.</param>249 /// <returns>The main window object as <see cref="Window" /> or null if no main window was found within the timeout.</returns>250 public Window GetMainWindow(AutomationBase automation, TimeSpan? waitTimeout = null)251 {252 WaitWhileMainHandleIsMissing(waitTimeout);253 var mainWindowHandle = MainWindowHandle;254 if (mainWindowHandle == IntPtr.Zero)255 {256 return null;257 }258 var mainWindow = automation.FromHandle(mainWindowHandle).AsWindow();259 if (mainWindow != null)260 {261 mainWindow.IsMainWindow = true;262 }263 return mainWindow;264 }265266 /// <summary>267 /// Gets all top level windows from the application.268 /// </summary>269 public Window[] GetAllTopLevelWindows(AutomationBase automation)270 {271 var desktop = automation.GetDesktop();272 var foundElements = desktop.FindAllChildren(cf => cf.ByControlType(ControlType.Window).And(cf.ByProcessId(ProcessId)));273 return foundElements.Select(x => x.AsWindow()).ToArray();274 }275276 private static Process FindProcess(int processId)277 {278 try279 {280 var process = Process.GetProcessById(processId);281 return process;282 }283 catch (Exception ex)284 {285 throw new Exception("Could not find process with id: " + processId, ex);286 }287 }288289 private static Process[] FindProcess(string executable)290 {291 return Process.GetProcessesByName(Path.GetFileNameWithoutExtension(executable));292 }293 }294}
...
Utils.cs
Source:Utils.cs
...18 {19 str24hour = str24hour.Replace(":", "").PadLeft(4, '0');20 return TimeSpan.ParseExact(str24hour, new string[] { "hhmm", @"hh\:mm" }, CultureInfo.InvariantCulture);21 }22 public static Process[] FindProcess(string executable)23 {24 return Process.GetProcessesByName(Path.GetFileNameWithoutExtension(executable));25 }26 public static IEnumerable<Window> GetTopLevelWindowsByClassName(AutomationBase automation, string className)27 {28 var desktop = automation.GetDesktop();29 var foundElements = desktop.FindAllChildren(cf => cf30 .ByControlType(ControlType.Window)31 .And(cf.ByClassName(className)));32 //This expression right here eats the CPU because of the frequent COM calls33 return foundElements.Select(x => x.AsWindow());34 }35 public static IEnumerable<Window> GetWindowsByClassNameAndProcessNameWithTimeout(AutomationBase automation, string processName, string className, TimeSpan timeout)36 {37 //Once the Retry.While API is asynchronous, I'll make most of these functions async38 //As using Task.Run() would provide no benefits of async as the function blocks the whole thread and each call would spawn a new thread39 //As of now the Retry.While API doesn't support cancellation tokens either, I'm going to add cancellation token stuff too once it does40 return Retry.WhileEmpty(() =>41 {42 var processIDs = FindProcess(processName).Select(x => x.Id);43 return GetTopLevelWindowsByClassName(automation, className).Where(x => processIDs.Contains(x.Properties.ProcessId));44 }, timeout, TimeSpan.FromMilliseconds(500), true, true).Result;45 }46 public static void ClickButtonInWindowByText(Window window, string text)47 {48 var button = (Button)Retry.Find(() => window.FindFirstDescendant(x => x.ByText(text).And(x.ByControlType(ControlType.Button))).AsButton(),49 new RetrySettings50 {51 Timeout = TimeSpan.FromSeconds(10),52 Interval = TimeSpan.FromMilliseconds(500)53 }54 );55 button.WaitUntilClickable(TimeSpan.FromSeconds(5))56 .WaitUntilEnabled(TimeSpan.FromSeconds(5)).Invoke();...
FindProcess
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using FlaUI.Core;7using FlaUI.Core.AutomationElements;8using FlaUI.Core.AutomationElements.Infrastructure;9using FlaUI.Core.Definitions;10using FlaUI.Core.Tools;11using FlaUI.UIA3;12{13 {14 static void Main(string[] args)15 {16 var application = FlaUI.Core.Application.Attach(ProcessHelper.FindProcess("notepad.exe"));17 var automation = new UIA3Automation();18 var window = application.GetMainWindow(automation);19 var textBox = window.FindFirstDescendant(cf => cf.ByControlType(ControlType.Edit)).AsTextBox();20 textBox.EmulateTyping("Hello World");21 }22 }23}
FindProcess
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using FlaUI.Core;7using FlaUI.Core.AutomationElements;8using FlaUI.Core.AutomationElements.Infrastructure;9using FlaUI.Core.Definitions;10using FlaUI.Core.Input;11using FlaUI.Core.WindowsAPI;12using FlaUI.UIA3;13using System.Diagnostics;14using System.Windows.Forms;15{16 {17 static void Main(string[] args)18 {19 var app = FlaUI.Core.Application.Attach(2);20 var window = app.GetMainWindow();21 var button = window.FindFirstDescendant(x => x.ByText("Button")).AsButton();22 button.Click();23 Console.ReadLine();24 }25 }26}27using System;28using System.Collections.Generic;29using System.Linq;30using System.Text;31using System.Threading.Tasks;32using FlaUI.Core;33using FlaUI.Core.AutomationElements;34using FlaUI.Core.AutomationElements.Infrastructure;35using FlaUI.Core.Definitions;36using FlaUI.Core.Input;37using FlaUI.Core.WindowsAPI;38using FlaUI.UIA3;39using System.Diagnostics;40using System.Windows.Forms;41{42 {43 static void Main(string[] args)44 {45 var app = FlaUI.Core.Application.Attach(3);46 var window = app.GetMainWindow();47 var button = window.FindFirstDescendant(x => x.ByText("Button")).AsButton();48 button.Click();49 Console.ReadLine();50 }51 }52}53using System;54using System.Collections.Generic;55using System.Linq;56using System.Text;57using System.Threading.Tasks;58using FlaUI.Core;59using FlaUI.Core.AutomationElements;60using FlaUI.Core.AutomationElements.Infrastructure;61using FlaUI.Core.Definitions;62using FlaUI.Core.Input;63using FlaUI.Core.WindowsAPI;64using FlaUI.UIA3;65using System.Diagnostics;66using System.Windows.Forms;67{68 {69 static void Main(string[] args)70 {71 var app = FlaUI.Core.Application.Attach(4);72 var window = app.GetMainWindow();73 var button = window.FindFirstDescendant(x => x.ByText("Button")).AsButton();74 button.Click();75 Console.ReadLine();76 }
FindProcess
Using AI Code Generation
1using System;2using System.Diagnostics;3using FlaUI.Core;4using FlaUI.Core.AutomationElements;5using FlaUI.Core.Definitions;6using FlaUI.Core.Input;7using FlaUI.UIA3;8using FlaUI.Core.Conditions;9using System.Threading;10{11 {12 static void Main(string[] args)13 {14 var application = FlaUI.Core.Application.Launch("C:\\Windows\\System32\\calc.exe");15 var mainWindow = application.GetMainWindow(Automation);16 var button7 = mainWindow.FindFirstDescendant(c => c.ByName("7"));17 button7.Click();18 var button9 = mainWindow.FindFirstDescendant(c => c.ByName("9"));19 button9.Click();20 var buttonPlus = mainWindow.FindFirstDescendant(c => c.ByName("+"));21 buttonPlus.Click();22 var button8 = mainWindow.FindFirstDescendant(c => c.ByName("8"));23 button8.Click();24 var buttonEqual = mainWindow.FindFirstDescendant(c => c.ByName("="));25 buttonEqual.Click();26 application.WaitWhileMainHandleIsMissing();27 }28 static AutomationBase Automation => new UIA3Automation();29 }30}
FindProcess
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using FlaUI.Core;7using FlaUI.Core.AutomationElements;8using FlaUI.UIA3;9{10 {11 static void Main(string[] args)12 {13 var automation = new UIA3Automation();14 var window = FlaUI.Core.Application.FindProcess(automation, 0, "notepad").GetMainWindow(automation);15 window.Focus();16 var textBox = window.FindFirstDescendant(cf => cf.ByControlType(FlaUI.Core.Definitions.ControlType.Edit)).AsTextBox();17 textBox.Enter("Hello world");18 Console.ReadKey();19 }20 }21}22using System;23using System.Collections.Generic;24using System.Linq;25using System.Text;26using System.Threading.Tasks;27using FlaUI.Core;28using FlaUI.Core.AutomationElements;29using FlaUI.UIA3;30{31 {32 static void Main(string[] args)33 {34 var automation = new UIA3Automation();35 var window = FlaUI.Core.Application.FindProcess(automation).GetMainWindow(automation);36 window.Focus();37 var textBox = window.FindFirstDescendant(cf => cf.ByControlType(FlaUI.Core.Definitions.ControlType.Edit)).AsTextBox();38 textBox.Enter("Hello world");39 Console.ReadKey();40 }41 }42}
FindProcess
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using FlaUI.Core;7using FlaUI.Core.AutomationElements;8using FlaUI.Core.Conditions;9using FlaUI.Core.Definitions;10using FlaUI.Core.EventHandlers;11using FlaUI.Core.Input;12using FlaUI.Core.Tools;13using FlaUI.Core.WindowsAPI;14using FlaUI.UIA3;15using FlaUI.UIA3.EventHandlers;16using FlaUI.UIA3.Patterns;17using FlaUI.UIA3.Tools;18using System.Diagnostics;19{20 {21 static void Main(string[] args)22 {23 var automation = new UIA3Automation();24 var app = FlaUI.Core.Application.Attach("notepad");25 var process = app.FindProcess("notepad");26 var mainWindow = process.GetMainWindow(automation);27 var textBox = mainWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Edit)).AsTextBox();28 textBox.Enter("Hello World!");29 var button = mainWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Button)).AsButton();30 button.Click();31 System.Threading.Thread.Sleep(2000);32 process.CloseMainWindow();33 }34 }35}
FindProcess
Using AI Code Generation
1using System;2using System.Diagnostics;3using System.Threading;4using FlaUI.Core;5using FlaUI.Core.AutomationElements;6using FlaUI.Core.Input;7using FlaUI.Core.Tools;8using FlaUI.UIA3;9using static FlaUI.Core.Definitions.NativeMethods;10{11 {12 static void Main(string[] args)13 {14 FlaUI.Core.Application app = FlaUI.Core.Application.Attach(Process.GetProcessesByName("notepad")[0].Id);15 var automation = new UIA3Automation();16 var mainWindow = app.GetMainWindow(automation);17 var edit = mainWindow.FindFirstDescendant(cf => cf.ByControlType(FlaUI.Core.Definitions.ControlType.Edit));18 edit.AsTextBox().Text = "Hello World";19 app.Close();20 }21 }22}
FindProcess
Using AI Code Generation
1using System;2using FlaUI.Core;3using FlaUI.Core.AutomationElements;4using FlaUI.Core.Conditions;5using FlaUI.Core.Definitions;6using FlaUI.Core.Input;7using FlaUI.Core.Tools;8using FlaUI.UIA3;9using System.Windows.Forms;10using System.Threading;11{12 {13 static void Main(string[] args)14 {15 var automation = new UIA3Automation();16 var process = FlaUI.Core.Application.FindProcess("notepad");17 if (process != null)18 {19 var window = process.MainWindow;20 var textBox = window.FindFirstDescendant(cf => cf.ByControlType(ControlType.Edit)).AsTextBox();21 textBox.Text = "Hello World!";22 Console.WriteLine("Text set successfully");23 }24 {25 Console.WriteLine("Process not found");26 }27 Console.ReadLine();28 }29 }30}31public string Text { get; set; }32using System;33using FlaUI.Core;34using FlaUI.Core.AutomationElements;35using FlaUI.Core.Conditions;36using FlaUI.Core.Definitions;37using FlaUI.Core.Input;38using FlaUI.Core.Tools;39using FlaUI.UIA3;40using System.Windows.Forms;41using System.Threading;42{43 {44 static void Main(string[] args)45 {46 var automation = new UIA3Automation();47 var process = FlaUI.Core.Application.FindProcess("notepad");48 if (process != null)49 {50 var window = process.MainWindow;
FindProcess
Using AI Code Generation
1using System;2using System.Diagnostics;3using FlaUI.Core;4using FlaUI.Core.AutomationElements;5using FlaUI.Core.Definitions;6using FlaUI.Core.Input;7using FlaUI.Core.WindowsAPI;8using FlaUI.UIA3;9using System.Windows.Forms;10using System.Threading;11{12 {13 static void Main(string[] args)14 {15 var application = FlaUI.Core.Application.Launch("notepad.exe");16 var automation = new UIA3Automation();17 var window = application.GetMainWindow(automation);18 Thread.Sleep(2000);19 window.Close();20 }21 }22}
FindProcess
Using AI Code Generation
1using System;2using System.Diagnostics;3using FlaUI.Core;4using FlaUI.Core.AutomationElements;5using FlaUI.Core.Definitions;6using FlaUI.Core.Input;7using FlaUI.Core.WindowsAPI;8using FlaUI.UIA3;9using FlaUI.Core.Tools;10{11 {12 static void Main(string[] args)13 {14 using (var automation = new UIA3Automation())15 {16 var process = FlaUI.Core.Application.FindProcess("notepad");17 var app = FlaUI.Core.Application.Attach(process);18 var window = app.GetMainWindow(automation);19 var textBox = window.FindFirstDescendant(cf => cf.ByAutomationId("15")).AsTextBox();20 textBox.Enter("Hello World!");21 var saveButton = window.FindFirstDescendant(cf => cf.ByAutomationId("1")).AsButton();22 saveButton.Click();23 var saveAsDialog = window.FindFirstDescendant(cf => cf.ByAutomationId("1000")).AsWindow();24 var fileNameTextBox = saveAsDialog.FindFirstDescendant(cf => cf.ByAutomationId("1001")).AsTextBox();25 fileNameTextBox.Enter("test.txt");26 var saveButton2 = saveAsDialog.FindFirstDescendant(cf => cf.ByAutomationId("1")).AsButton();27 saveButton2.Click();28 var yesButton = saveAsDialog.FindFirstDescendant(cf => cf.ByAutomationId("6")).AsButton();29 yesButton.Click();30 }31 }32 }33}34using System;35using System.Diagnostics;
FindProcess
Using AI Code Generation
1using System;2using System.Diagnostics;3using FlaUI.Core;4using FlaUI.Core.AutomationElements;5using FlaUI.Core.Input;6using FlaUI.Core.Definitions;7using FlaUI.Core.WindowsAPI;8using FlaUI.UIA3;9using FlaUI.Core.Conditions;10{11 {12 static void Main(string[] args)13 {14 var process = FlaUI.Core.Application.FindProcess("notepad.exe");15 var processId = process.Id;16 var processObject = Process.GetProcessById(processId);17 var app = FlaUI.Core.Application.Launch(processObject);18 var automation = new UIA3Automation();19 var window = app.GetMainWindow(automation);20 var editBox = window.FindFirstDescendant(cf => cf.ByAutomationId("15"));21 editBox.Focus();22 editBox.AsTextBox().Text = "Hello World";23 var menuItem = window.FindFirstDescendant(cf => cf.ByName("File"));24 Mouse.Instance.Location = menuItem.GetClickablePoint();25 Mouse.Instance.Click(MouseButton.Left);26 var menuFile = window.FindFirstDescendant(cf => cf.ByName("File"));27 Mouse.Instance.Location = menuFile.GetClickablePoint();28 Mouse.Instance.Click(MouseButton.Left);29 var menuExit = window.FindFirstDescendant(cf => cf.ByName("Exit"));30 Mouse.Instance.Location = menuExit.GetClickablePoint();31 Mouse.Instance.Click(MouseButton.Left);32 System.Threading.Thread.Sleep(2000);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!