通过Win32 SendMessage从c#发送byte [] [英] Send byte[] from c# via Win32 SendMessage

查看:156
本文介绍了通过Win32 SendMessage从c#发送byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些代码从c ++移植到c#,并且在使PostMessage在c#应用程序中正常工作时遇到了一些麻烦.我对MFC的东西还不太好,我认为我在犯一些基本的错误.在c ++代码中发生的是将字节数组发布到窗口:

I'm working on porting some code from c++ to c#, and I'm having some trouble getting PostMessage to work in the c# app. I'm not very good (yet) at MFC stuff, and I think I'm making a few basic mistakes. What happens in the c++ code is that a byte array is posted to a window:

unsigned long result[5] = {0};
//Put some data in the array
unsigned int res = result[0];
Text winName = "window name";
HWND hWnd = FindWindow(winName.getConstPtr(), NULL);
BOOL result = PostMessage(hWnd, WM_COMMAND, 10, res);

我正在使用以下c#代码(基于代码此处),以尝试执行相同的操作:

I'm using the following c# code (based on code here) in an attempt to do the same thing:

[DllImport("User32.dll", EntryPoint = "FindWindow")]
public static extern Int32 FindWindow(String lpClassName, String lpWindowName);

[DllImport("User32.dll", EntryPoint = "PostMessage")]
public static extern int PostMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);

[StructLayout(LayoutKind.Sequential)]
public struct COPYDATASTRUCT
{
    public IntPtr dwData;
    public int cbData;
    [MarshalAs(UnmanagedType.SafeArray)]
    public byte[] lpData;
}

public static int sendWindowsByteMessage(int hWnd, int wParam, byte[] data)
{
    int result = 0;

    if (hWnd > 0)
    {
         int len = data.Length;
         COPYDATASTRUCT cds;
         cds.dwData = (IntPtr)100;
         cds.lpData = data;
         cds.cbData = len + 1;
         result = PostMessage(hWnd, WM_COPYDATA, wParam, ref cds);
    }

    return result;
}

byte[] result = getResults();
int hWnd = MessageHelper.FindWindow(null, "window name");
int status = MessageHelper.sendWindowsByteMessage(hWnd, 10, result);

status的值始终为0,根据PostMessage的文档,这表示失败.任何关于我正在犯的错误(可能很简单)的指针?

The value of status is always 0, which according to the docs on PostMessage means failure. Any pointers on the (probably simple) mistakes I'm making?

推荐答案

WM_ COPYDATA必须发送而不是发布.

WM_ COPYDATA must be sent rather than posted.

我不确定您的byte []封送处理是否正确.

I'm not sure that your byte[] marshaling is right either.

这篇关于通过Win32 SendMessage从c#发送byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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