Logging Control Events in WinForms Application

 
Jul 17, 2012
 
In a Winforms Application with more than 100 forms a new requirement has come up.
Per requirement all the Events (button_Click, text_Changed ...) in any form needs to be logged to a log file.
This has to be done without adding new code to any of the forms. Meaning implementation has to be done globally.

Any framework available or suggestions would be appreciated.



Thanks
Vivek



50   50
Jul 30, 2012
You can use Logging Application Block.

http://msdn.microsoft.com/en-us/library/ff647183.aspx

-
Pramod

50   50
Jul 30, 2012
You can use Logging Application Block.

http://msdn.microsoft.com/en-us/library/ff647183.aspx

-
Pramod

65   95.6
Aug 04, 2012
Hi, Vivek.

It's impossible without changing the forms. You would need to subclass and introduce your own events.

However, a catch-all solution would be to implement your own message filter by implementing IMessageFilter, and calling Application.AddMessageFilter(myMessageFilter) in your startup code.

In the message filter you could catch every event. Below is an example that I used in one of my apps (had to restrict the usage of function keys). Using this method though could be daunting if you're trying to catch events for certain input fields, and could impact the responsiveness of your app if the logic is lengthy.

Hope this helps,

Mike

In your startup code (Main sub): Application.AddMessageFilter(New MyMessageFilter())
.
.
.

Public Class MyMessageFilter
    Implements IMessageFilter

    ' WIN32 API:
    Declare Function GetKeyState Lib "user32" Alias "GetKeyState" (ByVal nVirtKey As Integer) As Short
'
' Add mouse handler here too...
'

    Const WM_SYSKEYDOWN As Integer = &H104  ' System Key Down
    Const WM_TIMER As Integer = &H113       ' Timer message


    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        If m.Msg <> WM_SYSKEYDOWN Then Return False ' Handle only system keys

        If GetKeyState(Keys.F4) < 0 Then
            Return True     ' We handled Alt-F4
        End If

       If GetKeyState(Keys.A) < 0 Then    ' Alt-A was pressed
            GlobalEvents.RaiseAltAPressed()
            Return True     ' We handled Alt-A it
        End If

        If GetKeyState(Keys.X) < 0 Then     ' Alt-X was pressed
            GlobalEvents.RaiseAltXPressed()
            Return True     ' We handled Alt-X
        End If

        If GetKeyState(Keys.M) < 0 Then     ' Alt-M was pressed
            GlobalEvents.RaiseShowMap(Nothing)
            Return True     ' We handled it
        End If

        Return False    ' We didn't handle the message. Pass it on.

    End Function