Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET 2005 - "Global" Event Handler?

Suppose that for every Form in a WinForms application, you want to change the cursor to the WaitCursor. The obvious way to do this would be to add the code to every place where a form is instantiated/shown:

Try
    Me.Cursor = Cursors.WaitCursor

    Dim f As New frmMyForm
    f.Show()

Catch ex As Exception
    Throw
Finally
    Me.Cursor = Cursors.Default
End Try

However, I was wondering if there is a way to tell your application, "Whenever any form Load event fires, show a WaitCursor. When the form event Shown is complete, set the cursor back to Default." This way, the Me.Cursor code could be only in one place and not scattered throughout the application - and not forgotten to put it in to each form instantiation.

I suppose you could subclass the regular Form class and add the cursor settings in an overridden event, but I believe you lose the visual designer capability when you subclass the Form object.

like image 712
HardCode Avatar asked Feb 13 '09 15:02

HardCode


3 Answers

Subclassing is an option, you don't loose the designer as long as you don't set the superclass as mustinherit, it doesn't really like that.

like image 72
chrissie1 Avatar answered Nov 13 '22 18:11

chrissie1


To answer your question - there are no global .Net events to achieve what you want. There isn'y any pure .net solution to this. You could take a look at Aspect Orientated Programming and Cross Cutting Concerns - there may be an AOP solution to this (some googling will get you started then post back here for details).

However, what follows is more of an idea rather than a complete solution as to how you might achieve this using win32 messaging.

  1. You need to work out which win32 messages correspond to the Load event and if there is a win32 message that always happens after the load event. One candidate for the load event might be WM_SHOWWINDOW but I'm not sure.
  2. Write a message filter class (i.e. implement IMessageFilter).
  3. In the message filter class's PreMessageFilter method check the message type and if it is a WM_SHOWWINDOW (or whatever) message with the correct paramters then you can set/reset the cursor (using Cursor.Current = Cursors.WaitCursor - again you need to test this)
like image 29
ng5000 Avatar answered Nov 13 '22 19:11

ng5000


Another option that wouldn't involve subclassing is to add an extension method to the Form type. Then you could just call your extension method (something like ShowAndWait()) instead of show. You might even be about to call is Show if you overload it with a different signature.

like image 1
Jacob Adams Avatar answered Nov 13 '22 19:11

Jacob Adams