I try to get a window active to send keyboard inputs using
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
IntPtr calcWindow = FindWindow(null, "Calculator");
if (SetForegroundWindow(calcWindow))
SendKeys.Send("10{ }10=");
}
I am new to c# and i saw i need to put the exact name that apears on the taskbar, but i try to sent keyboard events to DOSBox which the name of the window i want to select has a weird name that i tried to write multiple times but i didnt get the right thing, do you know how i can browse the windows already opened and select this one or how can i get the exact name
CodePudding user response:
You can use System.Diagnostics.Process
to find the process. You can find the process by its ProcessName
and then get its MainWindowHandle
.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
// find the process by its name, this is the process name and is not the window name
System.Diagnostics.Process process = System.Diagnostics.Process.GetProcesses()
.FirstOrDefault(p => p.ProcessName.Equals("DOSBox"));
if(process != null)
{
IntPtr calcWindow = process.MainWindowHandle;
SetForegroundWindow(calcWindow);
if (SetForegroundWindow(calcWindow))
SendKeys.SendWait("10{ }10=");
}
}