C#SendMessage到C ++ WinProc [英] C# SendMessage to C++ WinProc

查看:86
本文介绍了C#SendMessage到C ++ WinProc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从C#向C ++ WindowProc发送一个字符串。关于SO,有许多与此相关的问题,但是没有一个答案对我有用。情况如下:

I need to send a string from C# to a C++ WindowProc. There are a number of related questions on SO related to this, but none of the answers have worked for me. Here's the situation:

PInvoke:
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, string lParam);

C#:
string lparam = "abc";
NativeMethods.User32.SendMessage(handle, ConnectMsg, IntPtr.Zero, lparam);

C++:
API LRESULT CALLBACK HookProc (int code, WPARAM wParam, LPARAM lParam)
{       
    if (code >= 0)
    {
        CWPSTRUCT* cwp = (CWPSTRUCT*)lParam;
                ...
        (LPWSTR)cwp->lParam   <-- BadPtr
                ...
    }

    return ::CallNextHookEx(0, code, wParam, lParam);
}

我尝试了许多不同的方法,将字符串编组为LPStr, LPWStr还尝试从非托管内存创建IntPtr,并使用Marshal.WriteByte对其进行写入。

I've tried a number of different things, Marshalling the string as LPStr, LPWStr, also tried creating an IntPtr from unmanaged memory, and writing to it with Marshal.WriteByte.

指针在C ++端是正确的内存位置,但是数据不在那里。我缺少什么?

The pointer is the correct memory location on the C++ side, but the data isn't there. What am I missing?

推荐答案

对于C ++ LPWSTR LPSTR 参数,您需要在DllImport中使用C# StringBuilder

For C++ LPWSTR or LPSTR parameters you need to use the C# StringBuilder in your DllImport.

对于C ++ LPCWSTR LPCSTR 参数,您需要使用C# string 在您的DllImport中。

For C++ LPCWSTR or LPCSTR parameters you need to use the C# string in your DllImport.

这篇关于C#SendMessage到C ++ WinProc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆