views:

455

answers:

3

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.

+2  A: 

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)
ng5000
Sounds like an idea. Thanks! I'll look into this.
HardCode
+3  A: 

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.

chrissie1
+1  A: 

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.

Jacob Adams
I might be confusing my terminology, but aren't extension methods new to VS.NET 2008? I'm using 2005. If not, then I'll try this out.
HardCode
You are correct. They are new to 2008
Jacob Adams