Can anyone tell me were I am making mistake in the snippet

梦想的初衷 提交于 2019-12-06 07:10:43

SampleProc.Method .MethodHandle.Value.ToInt32()

Just use SampleProc. If that fails, try marshalling it to a FunctionPointer.

The delegate instance does not need to be static. No idea why you think it should.

I think you need to declare your delegate instance at the form level, like this:

public partial class Form1 : Form
{
    [DllImport("coredll.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    const int GWL_WNDPROC = -4;
    public delegate int WindProc(IntPtr hWnd, uint msg, 
        long Wparam, long lparam);
    private WindProc _SampleProc;
    public Form1()
    {
        InitializeComponent();
        _SampleProc = new WindProc(SubclassWndProc);
        SetWindowLong(this.Handle, GWL_WNDPROC,
            _SampleProc.Method.MethodHandle.Value.ToInt32());

    }
    public int SubclassWndProc(IntPtr  hwnd, uint  msg, 
        long  Wparam, long  lparam)
    {
        return 1;
    }

Your original delegate instance was being declared in the form's constructor, where it immediately went out of scope (and thus wasn't around anymore to be called back to).

There might be other problems with your sample, too.

You are working with the compact framework, right? Are you doing everything from the same process?

I have experienced this kind of trouble myself, if the process where the window is created is not the same process as the message stems from. However I actively used SendMessage to send a message. If I did this from a different process, I got the "send error report" page. I now have found out, that if the SendMessage comes from the same process, things work fine.

In the above you could probably replace process with thread, although i am no sure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!