How can I ensure my C# console application is always in front? e.i. if a person clicks away from the console, how can I detect that the console has lost the focus an bring it back to front? I have this C# console application that is waiting for users to scan bar codes, if for some reason someone clicks away from the console window then the barcode data will be "lost". I took a look at this code posted on another thread;however, I can not seem to get this to work for me: bring a console window to front in c# This code thanks to @ILan keeps the console ontop of all windows, but it does not set the "focus" to keep capturing the incoming data.
class Program
{
[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
uint uFlags);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const uint SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_SHOWWINDOW = 0x0040;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
static void Main()
{
IntPtr handle = GetConsoleWindow();
SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
Console.WriteLine($"Hello handle: {handle}");
Console.ReadLine();
}
}