What is the correct declaration for SendMessage an

2019-08-05 08:19发布

I am confused by various declarations SendMessage. How do I know which one is correct?

In my c# winforms application (Windows 7) I use the following;

public class NativeMethods
{
    [DllImport("user32.dll")]
    // Currently uses 
    public static extern int SendMessage(IntPtr hWnd, uint wMsg, int wParam, int lParam);
    // Think I should probably be using 
    // public static extern int SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);
}

but the code that calls SendMessage is

 NativeMethods.SendMessage(this.tv.Handle, 277, 1, 0);

How do I figure out what parameters to use so that I can switch to the other declaration?

2条回答
孤傲高冷的网名
2楼-- · 2019-08-05 08:59

Look at the header files or at the MSDN documentation, and then you need a bit of extrapolation.

In your case, the actual C prototype is:

LRESULT WINAPI SendMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);

And the relevant typedefs are:

typedef unsigned int UINT;
typedef LONG_PTR LPARAM;
typedef UINT_PTR WPARAM;
typedef LONG_PTR LRESULT;

So the correct C# declaration would be:

[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, 
                                UIntPtr wParam, IntPtr lParam);

The IntPtr and UIntPtr have constructors that take a plain integer, so there is not problem to call it directly:

NativeMethods.SendMessage(this.tv.Handle, 277, new UIntPtr(1), IntPtr.Zero);

Actually, everything works as long as you respect the size of each of the parameters, but you have to be careful if you want your code to be portable between 32 and 64 bits.

查看更多
乱世女痞
3楼-- · 2019-08-05 09:01

Kirsten, this is an interop problem. Most C++ samples specify ints or uints for the parameters of SendMessage; the way C# would interpret the value doesn't really doesn't matter so long as

  • the bit patterns you pass are correct
  • the sizes are correct
  • the marshalling is appropriate

There's actually quite a bit to come to grips with here, too much for a stack overflow answer. The words you need with google are "interop" and "marshalling".

You should also be aware that you may have problems sending messages cross-process unless the sender has elevated permissions. And SendMessage is synchronous. Are you sure you don't want PostMessage?

查看更多
登录 后发表回答