::SendMessage(hWnd, WM_COPYDATA, 0, (LPARAM)(&cds))
//hWnd [in]: The handle of the C# window.
//cds [in]: A COPYDATASTRUCT structure.
这样方式来发送 2进制数据但是其中又涉及数据转换问题网上对此也有些解决方案但是多数都是只能发送串而不是任意 2进制数据废话不多说在此给出我解决方案跟大家分享
首先在C#/WPF中如何hook windows消息我就不多说了网上有大把介绍下面假设我们已经有了这么个消息处理:
public const WM_COPYDATA = 0x004A;
virtual IntPtr WndProc(IntPtr hwnd, msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
WM_COPYDATA:
{
...
}
...
}
}
那么我们需要用C写个并用dll导出:
//This function is to get data from COPYDATASTRUCT and save it to a managed data buffer.
//pDataStruct [in]: The data struct.
//pManagedData [out]: Buffer to save the data. If null, pdwDataLength will the buffer size
// needed; otherwise data will be copied and pdwDataLength s the actual size.
BOOL GetDataFromCOPYDATASTRUCT(void *pDataStruct, BYTE *pManagedData, DWORD &dwDataLength)
{
COPYDATASTRUCT *pTheData=(COPYDATASTRUCT *)pDataStruct;
(pTheData NULL)
{
FALSE;
}
(pTheData->cbData 0 || pTheData->lpData NULL)
{
FALSE;
}
(pManagedData NULL)
{
dwDataLength = pTheData->cbData;
TRUE;
}
(memcpy(pManagedData, pTheData->lpData, pTheData->cbData) != pManagedData)
{
FALSE;
}
dwDataLength = pTheData->cbData;
TRUE;
}
至于C#如何这段C解决方案就是众所周知PInvoke我也不罗嗦了
那么前面消息处理可以这样写:
virtual IntPtr WndProc(IntPtr hwnd, msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
WM_COPYDATA:
{
u uiDataLength = 0;
sBuffer = null;
//Todo: handle memory exception
(!GetDataFromCOPYDATASTRUCT(lParam, sBuffer, ref uiDataLength))
{
;//Todo: Handle error
;
}
(uiDataLength <= 0)
{
;
}
sBuffer = [uiDataLength];
(!GetDataFromCOPYDATASTRUCT(lParam, sBuffer, ref uiDataLength))
{
;//Todo: Handle error
;
}
//Use data
...
handled = true;
;
}
}
IntPtr ptrResult = IntPtr.Zero;
(handled)
{
ptrResult = IntPtr(1);
}
ptrResult;
}
这样我们就得到了想要 2进制数据. 如果发过来是串,比如UNICODE串,可以在Use data那行的下加上这个:
UnicodeEncoding encoding = UnicodeEncoding;
constructedString = encoding.GetString(sBuffer);
这样就得到了个能够使用串了.
最新评论