Help with IR Switch

Greetings all!

I have an IR switch that I use as a right click, and I use an Leonardo to do this:O) It seems to work great too in windows mode, but if used it in some apps like a game it acts funny. Like if I use it it will come on and stay on, and then if I try to trigger the switch (while its in the on position) then it makes it then trigger off. Very weird, and it only seems to do it in games.

const int InfraredSensorPin = 4;
pinMode(InfraredSensorPin,INPUT);
//InfraredSensorPin
    if(digitalRead(4) == HIGH){
    Mouse.press(MOUSE_RIGHT);
  }
  
  else{
    Mouse.release(MOUSE_RIGHT);
  }

I have tried a couple of different things like putting a delay here and there, but no luck. is there anything I can do to make sure that it goes off?

That's not a complete sketch, so my answer is a lot of gueswork.

If the infrared sensor is active longer than a few microseconds you'll send multiple mouse press events without a release event in between. The OS usually is able to overlook such errors but games often are a bit more picky because they react differently and need more detailed information.

Safe you read state and send keyboard events only in the case the state changes.

Alright Ill write up a state change, and sorry about the incomplete code, but it would be too much too post being several pages, but ill give that a try ty:O)