.NET 4.0 - AccessViolationException and WndProc

2020-03-13 09:14发布

问题:

I have this code snippet:

internal class MTool : NativeWindow
{
    private const int WM_LBUTTONDOWN = 0x0201;
    public event TipDeactivateEventHandler Deactivate;

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {           
        if( m.Msg == WM_LBUTTONDOWN )
        {
            if( this.Deactivate != null)
            {
                this.Deactivate();
            }
        }

        base.WndProc(ref m);
    }
}

When I run my program I get an AccessViolationException error at the line base.WndProc(ref m); and I don't know why.

Apparently this was ported over from .NET 2.0 to 4.0 and my theory is that there may be an alternate method used now in place of overriding WndProc. Is this case? If not why am I getting this exception?

回答1:

I fixed it by adding this attribute above the method:

[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]

Then surrounding the line where the exception occurs with a try/catch. I found this information here.



回答2:

The documentation for WndProc shows demanding full-trust. have you tried that? e.g.:

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
internal class MTool : NativeWindow
{
    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    protected override void WndProc(ref Message m)
    {
//...


回答3:

I suspect there's something larger happening in your code. Based on your snippet, I would try:

  1. Comment out the WndProc override, does this still repro by crashing somewhere else?
  2. Make the WndProc only invoke "base.WndProc(ref msg)". Do you still get the same error? What's the callstack? Is there any more of your code deeper in the stack?
  3. With the snippet as-is, is this only happening when WM_LBUTTONDOWN? When this throws that exception what is hooked to that Deactivate handler?

If these aren't practical to try, you probably need to update the snippet to explain better what you're trying to do.