Use Keyboard.IsKeyDown in C# console application - c#

I'm writing an console application witch Displaying certain data on the console screen, than checking for user input from the keyboard and finally handleing it by need. all single threaded.
For that i tried using Keyboard.IsKeyDown Method from System.Windows.Input namespace. and visual studio wo'nt allow it.
Does anyone knows why and can help me?
I dont see other way implementing that logic using only one thread and no timer's.

Use Console.ReadKey() to read input from the keyboard in a console application.
Note that this is a blocking call. If you don't want to block, combine with Console.KeyAvailable. For example, this program will loop and display if a key is pressed every 10th of a second:
static void Main(string[] args)
{
do
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey();
Console.WriteLine(key.Key);
}
else
{
Console.WriteLine("No key pressed");
}
System.Threading.Thread.Sleep(100);
} while (true);
}

Related

Stop Console Application from pausing on Pause Evemt

I've implememted a small Console Application that checks how long a programm is running. I then tried to run the application and everything is working fine. However then i hit (by accident) the "pause" key on my Keyboard and the programm stopped executing.
Is there a way to handle this event in a Console Application to suppress this pausing?
Update:
class Program
{
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(2000);
var p = Process.GetProcessesByName("wineks");
if (p != null)
{
Console.WriteLine("Found Process. Close it please");
Console.ReadKey();
}
}
}
}
That is basically my code. It is only asking the user to close a specific process. If I know hit the Pause Button on my Keyboard before I see the message, the message will never appear because the application freezes and seems like paused.
From browsing in the Internet I know that the key I press has the Name Pause and the key is sending some kind of Event or Signal to the Console.
Actually the Console does not have a way to raise KeyPress events , you can however try some looped approach to handle any key press done accidentally . Refer to this stackoverflow question here
Try inserting these lines before GetProcessByName
if (Console.KeyAvailable)
{
if (ConsoleKey.Pause == Console.ReadKey().Key)
continue;
}

Capture keyboard strokes with timing C# [duplicate]

I know there is a question for Windows Forms but it doesn't work in the console, or at least I couldn't get it to work. I need to capture key presses even though the console doesn't have focus.
You can create a global keyboard hook in a console application, too.
Here's complete, working code:
https://learn.microsoft.com/en-us/archive/blogs/toub/low-level-keyboard-hook-in-c
You create a console application, but must add a reference to System.Windows.Forms for this to work. There's no reason a console app can't reference that dll.
I just created a console app using this code and verified that it gets each key pressed, whether or not the console app has the focus.
EDIT
The main thread will run Application.Run() until the application exits, e.g. via a call to Application.Exit(). The simplest way to do other work is to start a new Task to perform that work. Here's a modified version of Main() from the linked code that does this
public static void Main()
{
var doWork = Task.Run(() =>
{
for (int i = 0; i < 20; i++)
{
Console.WriteLine(i);
Thread.Sleep(1000);
}
Application.Exit(); // Quick exit for demonstration only.
});
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
NOTE
Possibly provide a means to exit the Console app, e.g. when a special key combo is pressed depending on your specific needs. In the

Console window exits when debugging

I'm trying to run a program like a for loop. But when it starts debugging the console window disappears immediately. How do I stop this. I need something like press any key to continue.
Have a statement like
Console.Read()
That way, the console will remain until you press a key.
For more information, read here.
Write Console.ReadLine() or Console.Read() or Console.ReadKey() at the end of your program.
It will make your screen wait for your key press in order to exit.
I just found out that pressing the Ctrl + F5 key makes the console stay.
You didn't mention any example code. This is my example code. Program waits for pressing a key
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}

How to keep console window open

When I run my program, the console window seems to run and close. How to keep it open so I can see the results?
class Program
{
public class StringAddString
{
public virtual void AddString()
{
var strings2 = new string[] { "1", "2", "3", "4", "5","6", "7", "8", "9"};
Console.WriteLine(strings2);
Console.ReadLine();
}
}
static void Main(string[] args)
{
StringAddString s = new StringAddString();
}
}
Put a Console.Read() as the last line in your program. That will prevent it from closing until you press a key
static void Main(string[] args)
{
StringAddString s = new StringAddString();
Console.Read();
}
If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();
Like other answers have stated, the call to Console.ReadLine() will keep the window open until enter is pressed, but Console.ReadLine() will only be called if the debugger is attached.
There are two ways I know of
1) Console.ReadLine() at the end of the program. Disadvantage, you have to change your code and have to remember to take it out
2) Run outside of the debugger CONTROL-F5 this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)
Console.ReadKey(true);
This command is a bit nicer than readline which passes only when you hit enter, and the true parameter also hides the ugly flashing cursor while reading the result :) then any keystroke terminates
You forgot calling your method:
static void Main(string[] args)
{
StringAddString s = new StringAddString();
s.AddString();
}
it should stop your console, but the result might not be what you expected, you should change your code a little bit:
Console.WriteLine(string.Join(",", strings2));
You can handle this without requiring a user input.
Step 1. Create a ManualRestEvent at the start of Main thread
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
Step 2 . Wait ManualResetEvent
manualResetEvent.WaitOne();
Step 3.To Stop
manualResetEvent.Set();
Write Console.ReadKey(); in the last line of main() method. This line prevents finishing the console. I hope it would help you.
If your using Visual Studio just run the application with Crtl + F5 instead of F5. This will leave the console open when it's finished executing.
Use Console.Readline() at the end .Your code will not close until you close it manually.Since Readline waits for input that needs to be entered for your code hence your console will be open until you type some input.
For visual c# console Application use:
Console.ReadLine();
Console.Read();
Console.ReadKey(true);
for visual c++ win32 console application use:
system("pause");
press ctrl+f5 to run the application.
Make sure to useConsole.ReadLine();
to keep the preceeding Console.WriteLine(""); message from closing.
Console.Read()
-> Console stays open until you press a button on your keyboard
To be able to give it input without it closing as well you could enclose the code in a while loop
while (true)
{
<INSERT CODE HERE>
}
It will continue to halt at Console.ReadLine();, then do another loop when you input something.
If you're using Visual Studio, then the IDE has an option to keep the window open under
Tools > Options > Debugging >
Automatically close the console when debugging stops
Unlike CTRL + F5, this allows you to use breakpoints while debugging.

How do I need to modify my WinForms app to also run in the console?

I have a .NET WinForms app written in C#. In order to support batch operations, I'd now like to make the app able to run in the console.
Is it possible to have an app that detects on startup whether it is running in the console or not?
What modifications do I need to make in order to achieve this behaviour?
You should have a Program.cs file in your solution, this file contains a:
static void Main()
{
}
You'll notice in this method there is something like:
Application.Run(new Form1());
This is where your form is actually launched, so what you can do is modify your Main() to something like this:
static void Main(string[] args)
{
if(args.Length < 1)
{
Application.Run(new Form1());
return;
}
else
{
// Handle your command line arguments and do work
}
}
So if your program is invoked with no command line arguments, the windows form pops open and does its thing. Otherwise you do what you need to do via the command line and exit without ever showing a form.
You can allocate a Console for your WinForms app using the AllocConsole function. You can find more information about how to call this from C# on it's pinvoke page.
However, this will not make it a true console app and I've heard that there are some limitations, however, it might work depending on your exact needs.
You could use a main method in program.cs and detect whether command line parameters are passed in, if they are do batch processing, if not show the GUI.
public static void Main(string[] args)
{
if (args.count > 0) {
//batch
} else {
//gui
}
}

Categories