Invoking MessageBox from Scroll event of HScrollBar

A

Alexander Smirnov

Hello!
I need at some circumstances to show a message box from the Scroll
event handler of an HScrollBar component. But when I invoke
MessageBox.Show() the scroll event occurs again and again and I can
have up to about 50 message boxes on the screen. Something with
message queue, I suspect.
How to prevent this?

Thanks in advance.
 
P

Peter Duniho

Hello!
I need at some circumstances to show a message box from the Scroll
event handler of an HScrollBar component. But when I invoke
MessageBox.Show() the scroll event occurs again and again and I can
have up to about 50 message boxes on the screen. Something with
message queue, I suspect.
How to prevent this?

The simple answer is "don't do that".

It's not a good idea to execute complex UI code, such as displaying a
dialog box, in event handlers that deal with real-time, on-going user
interaction, such as scrolling a scroll bar. Why you think it would make
sense to the user to display a dialog box in response to scrolling, I
don't know (it sounds like very poor UI to me), but assuming you feel you
simply must do this, you need to do a couple of things:

* Instead of showing the dialog box immediately in the event handler,
use some mechanism to defer the action until after you've returned from
the scroll bar handling. For example, use Control.BeginInvoke() with the
form and a delegate that will show the dialog box.

Doing this will ensure that all of the click-and-drag sort of stuff in the
scroll bar handling sequence can complete before control gets passed off
to the dialog box's message pump.

* Disable the scroll bar before you show the dialog box and if
necessary, put an internal flag into your class that you can set to ensure
that you only show the dialog box once. I suspect that disabling the
scroll bar would be sufficient, but if you have trouble with that, the
flag should definitely work if used correctly. Set the flag in the scroll
bar event handler when you call Control.BeginInvoke() to show the dialog,
check the flag before calling Control.BeginInvoke() and only show the
dialog if it's cleared, and then clear the flag after returning from the
actual call to Form.ShowDialog() in your delegate responsible for showing
the dialog.

This is the key part that will ensure that the dialog box is only
displayed once. You could probably get away with just doing this part,
but IMHO it's a bad idea to display a dialog box from within the scroll
bar handling code, thus the first point above.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top