You can do this simply with API calls and a timer. Add this line to your form's using statements:
using System.Runtime.InteropServices;
Next, add these declarations to your form:
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
Finally, put a Timer on your form, and set its Enabled property to true
. In its Tick event, put this code:
IntPtr hWndNotepad = FindWindow(null, "Whatever.txt - Notepad");
IntPtr hWndForegroundWindow = GetForegroundWindow();
if (this.Handle != hWndForegroundWindow)
{
this.Visible = (hWndNotepad == hWndForegroundWindow);
}
I haven't tested this code, but it should work. The code is looking for a specific file to be open in Notepad; a different file would result in different text in the titlebar, so this code wouldn't work. I think that if you change the FindWindow call to FindWindow("notepad", null)
it would work with any open instance of Notepad (it might be "notepad.exe" - not sure).
Update: if you want your form to be visible if any instance of Notepad is open, you can instead put this code into your Timer's Tick event:
IntPtr hWndForegroundWindow = GetForegroundWindow();
bool NotepadIsForeground = false;
Process[] procs = Process.GetProcessesByName("notepad");
foreach (Process proc in procs)
{
if (proc.MainWindowHandle == hWndForegroundWindow)
{
NotepadIsForeground = true;
break;
}
}
if (this.Handle != hWndForegroundWindow)
{
this.Visible = NotepadIsForeground;
}
And you'll need this in your using directives:
using System.Diagnostics;
Also not tested, but I'm doing so well today, so why bother?