I would like to have my console app that runs for a while to give some options to the user at the end if at anytime during the process the user pressed the shift key. Is this possible?
+2
A:
Sure, run your processing tasks in another thread while polling for console input with ReadKey
(MSDN) in your main thread.
Thread thread = new Thread(() => DoWork());
thread.Start();
while (true) {
Thread.Sleep(10);
var keyInfo = Console.ReadKey();
if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
// take note of shift
}
}
If threading isn't an option (it should be) you'll have to periodically interrupt your processing to check the key input or you can create a hidden window and process keys through that.
Ron Warholic
2010-05-27 18:38:13
This looks promising, but my console app doesn't close when it's finished anymore.
adam0101
2010-06-01 14:05:04
Also, my flag for the shift key never gets updated. If I put a breakpoint inside the "if" statement and hold the shift key while running it, the breakpoint never gets hit.
adam0101
2010-06-01 14:13:06
It looks like it goes through the While loop once when it starts, and then doesn't do it again until "DoWork" has finished - which is too late by then.
adam0101
2010-06-01 14:18:03
+1
A:
I changed the infinite loop to one that looks for a flag that is set after my process finishes. I also changed how the Shift key was being looked for because it didn't look like Console.ReadKey() was doing anything for Shift. I'll still give Ron credit though for bringing up threading. This code tested out ok:
Dim thread As New System.Threading.Thread(AddressOf Generate)
thread.Start()
While _generating
System.Threading.Thread.Sleep(10)
If (System.Windows.Forms.Control.ModifierKeys And Windows.Forms.Keys.Shift) = Windows.Forms.Keys.Shift Then
_showOptions = True
End If
End While
adam0101
2010-06-01 14:39:58
Glad to hear you got it working. I realize now that `ReadKeys` will only pick up a non-modifier key--modifiers alone won't register. I'm somewhat surprised your solution works without a windows form considering I would expect `ModiferKeys` to use the windows message pump...
Ron Warholic
2010-06-01 14:54:47