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);
public Form1()
{
InitializeComponent();
WindProc 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;
}
Here is the sample which i was trying to take the window procedure of a form, this is how i do in C++ i get the windwproc easlily if i try the same in C# .net 3.5 i am unable to get the window proc,, after calling SetWindowLong API application hangs and it pops up some dont send report... i have read this is the way to get the window proc.. please let me know were i am making mistake...
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.
来源:https://stackoverflow.com/questions/1465864/can-anyone-tell-me-were-i-am-making-mistake-in-the-snippet