'C# forms check when a specific execute has been launched and then run my program
How would I make my program check if a certain application like "notepad" has focus and ultimately open my second form when it does have focus, closing that second form when it loses focus.
(I would Also like to include an updater so that if the checkbox is checked while "notepad" is closed keep the checkbox checked, but do not open my second form until "notepad" has been opened) I know this is a very specific question and hence why I couldn't find anything relative to this.
Here is a mockup of what I believe it would look like:
DLL import
getforeground window
Process g = "notepad"
if (g is Foreground window in front && checkbox.checked) // my checkbox i use to enable the program
{
show form two
}
else
{
hide form two
}
Solution 1:[1]
My solution for anyone who wants to only make their code run when a specific program is open. This is great for Mouse events + sending inputs when a specific program is opened. (Removes that craziness from happening when outside of that program)
FirstlyImport DLLs:
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
Second create this string to capture what window is active:
public string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
Reminder if you wish to test which application you have open just maker a timer on 1 second repeat and type this inside the timer:
Console.Writeline(GetForegroundWindow());
Once you know your applications name (Also shows the name on taskbar - not task manager) You will want to type:
if (GetActiveWindowTitle() == "Notepad") // change notepad to your program
{
// do what you want to do
}
Hopefully this helps someone like it helped me :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | James |