[request] is it possible to focus on process name --- tracked on GitHub

Asked by Chetan

tracked on Github: https://github.com/RaiMan/SikuliX1/issues/593
----------------------------------------------------------------------------------------------------

is it possible to focus on process name?
focus based on title does not work always for me

so i am getting process name from powershell using below command and wanted to pass it to focus like
app.focus("acrobat")

ps script
Get-Process | Where-Object { $_.Name -eq "Acrobat" }

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
RaiMan (raimund-hocke) said :
#1

accepted as feature request

Revision history for this message
Evelynemma (evelynemma) said :
#2

Certainly, focusing on a process by its name using PowerShell is possible and can be quite effective, especially when using applications that have inconsistent or varying window titles. The PowerShell command you provided, Get-Process | Where-Object { $_.Name -eq "Acrobat" }, retrieves the process with the name "Acrobat". Once you have the process information, you can manipulate the application's window focus using various methods.
https://fabvipbio.com/

To achieve this programmatically, you can make use of Windows API functions through PowerShell's .NET integration. One common approach is using the [DllImport] attribute to call the SetForegroundWindow function from the user32.dll library. This would allow you to bring the application window associated with the specified process name to the foreground.

Here's an example PowerShell code snippet that demonstrates this process:

powershell
Copy code
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;

public class User32 {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
}
'@

$process = Get-Process | Where-Object { $_.Name -eq "Acrobat" }

if ($process) {
    [User32]::SetForegroundWindow($process.MainWindowHandle)
} else {
    Write-Host "Process not found."
}
In this code, the MainWindowHandle property of the process provides the handle to the application's main window, which is then used to bring it to the foreground using the SetForegroundWindow function from user32.dll.

Remember that this approach requires administrative privileges and might not work as expected for all applications due to security and compatibility considerations. Additionally, focus manipulation can be disruptive, so be mindful when implementing this in your workflow.