There is such code:

int Switch5 = ProcessMemoryReaderApi.GetKeyState(0xA1); if ((Switch5 & 0x8000) != 0) { act = !act; if (act) Console.WriteLine("true"); else Console.WriteLine("false"); } 

When you press the SHIFT key - the program comes here. But! If you hold it and not let go - the bool act quickly changes from false to true. How can you make it so that when you press shift, act true, even if you keep it constant? And when you click on shift again - the variable is changed to false

  • Do you have code written in two languages ​​at once? Why two tags? - AK ♦
  • @AK, it’s Java that C # doesn’t matter in this code, for the difference is only in the console output - user300058
  • Has the meaning. Because, most likely, you will not be able to repeat your code not in Java, and therefore you will not receive an answer. You need to connect via using or import depending on # or java. - nick_n_a
  • You need to get the code of the key pressed, and put the block if the previous key is equal to the current one, or for all, or specifically for shift. There is somewhere a "key pressed" event, and a "key released". - nick_n_a
  • Bring the program to such a view that you could see 1) code (scancode) of the pressed key 2) sign of the key pressed or released. Then the question can be answered. - nick_n_a

1 answer 1

How about the easiest protection

 private volatile bool _IAmWorking; public void KeyEventHandler(EventArgs event) { if (_IAmWorking) return; _IAmWorking = true; ...... _IAmWorking = false; } 

For the single-threaded option, you can track when the button was pressed and when it was pressed

 private bool _canRunLogic = true; public void ShiftKeyDownEventHandler(EventArgs event) { if (!_canRunLogic) return; _canRunLogic = false; ...... } public void ShiftKeyUPEventHandler(EventArgs event) { _canRunLogic = true; } 
  • this will help if the application is multi-threaded, and _IAmWorking is labeled volatitle. In one thread, this situation will not. I think that there is one thread, because it is a simple question. - nick_n_a
  • @nick_n_a think that the keys will be pressed at breakneck speed from different streams? It's just about pressing one key - tym32167
  • I want to say that if the keys are pressed at a breakneck speed from different streams, then such a block will work :) Just ... it will work if there is a function “recursively” to be caused by carelessness, which is also a very rare case. - nick_n_a
  • @nick_n_a ok, added volatile, and the second option at the same time, let the author have a good time. - tym32167