开发者

Detect Shift key at any point during the execution of a console app

开发者 https://www.devze.com 2023-01-01 11:59 出处:网络
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

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?


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号