1

I can't believe I am having an issue with this, but such is life.

I have a button on a Winform with a click event that runs some code. I disable the button, run my code, then enable the button. The weird part is any click that happens on the button while disabled merely waits for the button to be enabled again, and then runs.

private void FooBar_Click(object sender, EventArgs e){
   Enabled = false;  //disable the form (yeah, i tried that)
   btnFooBar.Enabled = false;
   //DO SOME STUFF
   Enabled = true;
   btnFooBar.Enabled = true;
}

I tried adding a check to the beginning, but it is always true (cause it just waits for the execution to end) :

if(!btnFooBar.Enabled)
   { return;}

Is there a way for those disabled clicks to be ignored?

Limey
  • 2,642
  • 6
  • 37
  • 62
  • 3
    The problem is that you're tying up the UI thread so the button never actually gets disabled (You re-enable it again before the UI ever realizes you made the change). Look into async/await to overcome this problem. – itsme86 Mar 13 '18 at 19:41
  • 1
    if `//DO SOME STUFF` is a long running task you can use async/await as said. if not, no need to disable/enable it since all code runs in a single UI thread – Eser Mar 13 '18 at 19:43
  • 2
    If your long lasting operation is executed in the UI thread, the message pump (and thus the processing the mouse click) will be blocked until you exit the method. By the time the UI thread can process the pending mouse click the button is already enabled, again. See the answer here to see 3 different solutions for the problem: https://stackoverflow.com/a/36079335/5114784 – György Kőszeg Mar 13 '18 at 19:50
  • @taffer UI thread can not process mouse clicks if message pump is blocked.... (every winform app is executed in a single thread and has a single message pump) – Eser Mar 13 '18 at 19:54
  • @Eser: Yes, that's what I'm saying, too. :) And the same applies for keystrokes, updating invalidated UI and other windows messages as well. – György Kőszeg Mar 13 '18 at 19:56
  • I'm not sure why my winform wasn't single threading, but I was able to add a background worker for the button, and things a re working great! thanks – Limey Mar 13 '18 at 21:03

0 Answers0