I have an application that behaves as a windows forms and as a console application depending if I pass parameters or not. If I pass parameters it behaves as a console application.
In this last case, as a console application, I attach to the console using:
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
So at the beginning of the app, I call it as below:
AttachConsole(-1);
Later what I do is simply read the string parameter or parameters passed as a parameter in command line, and I return encrypted these strings. After It I wait for user key press using:
Console.ReadKey(true);
After user press any key I want to close the console window.
My problem is that when user press a key, the application does not continue, it still keeps waiting for a key because this key pressed is catched by the another attached console. So in order the application continues user needs to press key twice. On first key press, command prompt is printed again (this comes from the attached console).
How can I solve this?
UPDATE:
static void Main(string[] args)
{
if (args.Length == 0)
{
Application.Run(new MyForm());
}
else
{
// case args.Length > 0
Console.WriteLine("Start my formless app...");
new FormLessApp().Start(args);
}
}
ReadKey is performed within FormLessApp:
public class FormLessApp
{
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int input);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
public FormLessApp()
{
IntPtr ptr = GetForegroundWindow();
int u;
GetWindowThreadProcessId(ptr, out u);
Process process = Process.GetProcessById(u);
if (process.ProcessName == "cmd")
{
AttachConsole(process.Id);
Console.WriteLine("attached to console");
}
}
public void Start(string[] args)
{
// Do some things with args
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
To Reproduce:
Open a windows command prompt (cmd) and from there execute it as:
MyApp.exe param1 param2 .....