I'm trying to port some C++ code to C#, and one of the things that I need to do is use PostMessage to pass a byte array to another process' window. I'm trying to get the source code to the other program so I can see exactly what it's expecting, but in the meantime, here's what the original C++ code looks like:
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);
And here's what I have now:
[DllImport("User32.dll", SetLastError = true, EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
[DllImport("User32.dll", SetLastError = true, EntryPoint = "SendMessage")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
[StructLayout(LayoutKind.Sequential)]
public struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte[] lpData;
}
public const int WM_COPYDATA = 0x4A;
public static int sendWindowsByteMessage(IntPtr hWnd, int wParam, byte[] data)
{
int result = 0;
if (hWnd != IntPtr.Zero)
{
int len = data.Length;
COPYDATASTRUCT cds;
cds.dwData = wParam;
cds.lpData = data;
cds.cbData = len;
result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
}
return result;
}
//*****//
IntPtr hWnd = MessageHelper.FindWindow(null, windowName);
if (hWnd != IntPtr.Zero)
{
int result = MessageHelper.sendWindowsByteMessage(hWnd, wParam, lParam);
if (result == 0)
{
int errCode = Marshal.GetLastWin32Error();
}
}
Note that I had to switch from using PostMessage in C++ to SendMessage in C#.
So what happens now is that I'm getting both result and errCode to be 0, which I believe means that the message was not processed - and indeed looking at the other application, I'm not seeing the expected response. I have verified that hWnd != IntPtr.Zero, so I think that the message is being posted to the correct window, but the message data is wrong. Any ideas what I'm doing wrong?
Update
I'm still not having any luck after trying the suggestions in the comments. Here's what I've currently got:
[DllImport("User32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
public struct BYTEARRDATA
{
public byte[] data;
}
public static IntPtr IntPtrAlloc<T>(T param)
{
IntPtr retval = Marshal.AllocHGlobal(Marshal.SizeOf(param));
Marshal.StructureToPtr(param, retval, false);
return (retval);
}
public static void IntPtrFree(IntPtr preAllocated)
{
//Ignores errors if preAllocated is IntPtr.Zero!
if (IntPtr.Zero != preAllocated)
{
Marshal.FreeHGlobal(preAllocated);
preAllocated = IntPtr.Zero;
}
}
BYTEARRDATA d;
d.data = data;
IntPtr buffer = IntPtrAlloc(d);
COPYDATASTRUCT cds;
cds.dwData = new IntPtr(wParam);
cds.lpData = buffer;
cds.cbData = Marshal.SizeOf(d);
IntPtr copyDataBuff = IntPtrAlloc(cds);
IntPtr r = SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, copyDataBuff);
if (r != IntPtr.Zero)
{
result = r.ToInt32();
}
IntPtrFree(copyDataBuff);
copyDataBuff = IntPtr.Zero;
IntPtrFree(buffer);
buffer = IntPtr.Zero;
This is a 64 bit process trying to contact a 32 bit process, so there may be something there, but I'm not sure what.
The problem is that COPYDATASTRUCT is supposed to contain a pointer as the last member, and you're passing the entire array.
Take a look at the example on pinvoke.net: http://www.pinvoke.net/default.aspx/Structures/COPYDATASTRUCT.html
More info after comments:
Given these definitions:
const int WM_COPYDATA = 0x004A;
[StructLayout(LayoutKind.Sequential)]
struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
[DllImport("User32.dll", SetLastError = true, EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
[DllImport("User32.dll", SetLastError = true, EntryPoint = "SendMessage")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
I can create two .NET programs to test WM_COPYDATA. Here's the window procedure for the receiver:
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
label3.Text = "WM_COPYDATA received!";
COPYDATASTRUCT cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));
byte[] buff = new byte[cds.cbData];
Marshal.Copy(cds.lpData, buff, 0, cds.cbData);
string msg = Encoding.ASCII.GetString(buff, 0, cds.cbData);
label4.Text = msg;
m.Result = (IntPtr)1234;
return;
}
base.WndProc(ref m);
}
And the code that calls it using SendMessage:
Console.WriteLine("{0} bit process.", (IntPtr.Size == 4) ? "32" : "64");
Console.Write("Press ENTER to run test.");
Console.ReadLine();
IntPtr hwnd = FindWindow(null, "JimsForm");
Console.WriteLine("hwnd = {0:X}", hwnd.ToInt64());
var cds = new COPYDATASTRUCT();
byte[] buff = Encoding.ASCII.GetBytes(TestMessage);
cds.dwData = (IntPtr)42;
cds.lpData = Marshal.AllocHGlobal(buff.Length);
Marshal.Copy(buff, 0, cds.lpData, buff.Length);
cds.cbData = buff.Length;
var ret = SendMessage(hwnd, WM_COPYDATA, 0, ref cds);
Console.WriteLine("Return value is {0}", ret);
Marshal.FreeHGlobal(cds.lpData);
This works as expected when both the sender and receiver are 32 bit processes and when they're 64 bit processes. It will not work if the two processes' "bitness" does not match.
There are several reasons why this won't work for 32/64 or 64/32. Imagine that your 64 bit program wants to send this message to a 32 bit program. The lParam value passed by the 64 bit program is going to be 8 bytes long. But the 32 bit program only sees 4 bytes of it. So that program won't know where to get the data from!
Even if that worked, the size of the COPYDATASTRUCT structure is different. In 32 bit programs, it contains two pointers and a DWORD, for a total size of 12 bytes. In 64 bit programs, COPYDATASTRUCT is 20 bytes long: two pointers at 8 bytes each, and a 4-byte length value.
You have similar problems going the other way.
I seriously doubt that you'll get WM_COPYDATA to work for 32/64 or for 64/32.
This will work on 32bit sender to 64bit receiver, 64bit sender to 32bit receiver. Also work from 32 to 32, and 64 to 64. You don't even need to declare COPYDATASTRUCT. Very simple:
const int WM_COPYDATA = 0x004A;
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
static IntPtr SendMessage(IntPtr hWnd, byte[] array, int startIndex, int length)
{
IntPtr ptr = Marshal.AllocHGlobal(IntPtr.Size * 3 + length);
Marshal.WriteIntPtr(ptr, 0, IntPtr.Zero);
Marshal.WriteIntPtr(ptr, IntPtr.Size, (IntPtr)length);
IntPtr dataPtr = new IntPtr(ptr.ToInt64() + IntPtr.Size * 3);
Marshal.WriteIntPtr(ptr, IntPtr.Size * 2, dataPtr);
Marshal.Copy(array, startIndex, dataPtr, length);
IntPtr result = SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ptr);
Marshal.FreeHGlobal(ptr);
return result;
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr hWnd = FindWindow(null, "Target Window Tittle");
byte[] data = System.Text.Encoding.ASCII.GetBytes("this is the sample text");
SendMessage(hWnd, data, 0, data.Length);
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
byte[] b = new Byte[Marshal.ReadInt32(m.LParam, IntPtr.Size)];
IntPtr dataPtr = Marshal.ReadIntPtr(m.LParam, IntPtr.Size * 2);
Marshal.Copy(dataPtr, b, 0, b.Length);
string str = System.Text.Encoding.ASCII.GetString(b);
MessageBox.Show(str);
// m.Result = put result here;
return;
}
base.WndProc(ref m);
}
Could it be a 32 versus 64 bit problem?
Try setting COPYDATASTRUCT's dwData member to an IntPtr instead of an int.
See this thread for a related problem:
http://www.vistax64.com/net-general/156538-apparent-marshalling-related-problem-x64-but-works-x86.html
See the original definition of COPYDATASTRUCT:
http://msdn.microsoft.com/en-us/library/ms649010(VS.85).aspx
Here's the meaning of ULONG_PTR on x64:
http://msdn.microsoft.com/en-us/library/aa384255(VS.85).aspx
To store a 64-bit pointer value, use ULONG_PTR. A ULONG_PTR value is 32 bits when compiled with a 32-bit compiler and 64 bits when compiled with a 64-bit compiler.
In your IntPtrAlloc function, what's the SizeOf(param) giving you? I think it's going to be the size of a reference to an array, not the size of the array content. And so Windows will copy a .NET array reference into the other process, which is completely meaningless.
Pin the array, and use Marshal.UnsafeAddrOfPinnedArrayElement to get the proper value of lpData.
Related
I'm in the process of writing a basic .NET wrapper for the unmanaged Offline Registry Library. Currently, I'm working to implement a class, OfflineRegistryKey, which is modelled on Microsoft.Win32.RegistryKey but intended for use with offline Registry Hives rather than the live system Registry.
While trying to implement an equivalent to the GetValueNames() method, which enumerates values within a Registry key, I ran into some trouble trying to P/Invoke the unmanaged function OREnumValue from Offreg.dll. The only parameter I'm interested in in this case is the name of the value, or lpValueName.
My P/Invoke code for OREnumValue:
[DllImport("Offreg.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern uint OREnumValue(
SafeRegistryHandle Handle,
uint dwIndex,
IntPtr lpValueName,
ref uint lpcValueName,
IntPtr lpType,
IntPtr lpData,
ref uint lpcbData);
I call the function like this in my code:
public class OfflineRegistryKey : IDisposable
{
private readonly SafeRegistryHandle hKey;
public string[] GetValueNames()
{
uint dwIndex = 0;
while (true)
{
uint lpcValueName = 0;
uint lpcbData = 0;
uint returnValue = OREnumValue(hKey, dwIndex, IntPtr.Zero, ref lpcValueName, IntPtr.Zero, IntPtr.Zero, ref lpcbData);
if (returnValue == 0x0103) // ERROR_NO_MORE_ITEMS
{
break;
}
else if (returnValue == 0x00EA) // ERROR_MORE_DATA
{
// Do stuff...
}
else
{
throw new Win32Exception(returnValue);
}
dwIndex++;
}
}
}
Ideally, The call to OREnumKey would return 0xEA (ERROR_MORE_DATA), after which it would be called again until it reaches the end index and returns 0x103 (ERROR_NO_MORE_ITEMS).
The return value I'm getting (which throws an exception at runtime and halts execution on the first iteration of the loop) is 0x57 (ERROR_INVALID_PARAMETER), which leads me to believe that I've somehow screwed up the P/Invoke call. I would very much appreciate if someone with a greater knowledge of P/Invoke and the Windows API could provide me with some guidance.
Thanks!
Your P/Invoke declaration is not correct, because lpValueName does not accept NULL according to the documentation.
It's also defined as Unicode, so you should specify that.
[DllImport("Offreg.dll", CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint OREnumValue(
SafeRegistryHandle Handle,
uint dwIndex,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpValueName,
ref uint lpcValueName,
IntPtr lpType,
IntPtr lpData,
ref uint lpcbData);
Then you simply pass a pre-assigned buffer. Theoretically it could be 16383 characters, you could use ORQueryInfoKey to get the max size, or just allocate the whole thing. I suggest you allocate it only once, outside the loop.
public string[] GetValueNames()
{
const int ERROR_SUCCESS = 0;
const int ERROR_NO_MORE_ITEMS = 0x103;
const int ERROR_MORE_DATA = 0x00EA;
uint dwIndex = 0;
string lpValueName = new StringBuilder(16384);
while (true)
{
uint lpcValueName = 0;
uint lpcbData = 0;
uint returnValue = OREnumValue(hKey, dwIndex, IntPtr.Zero, ref lpcValueName, IntPtr.Zero, IntPtr.Zero, ref lpcbData);
if (returnValue == ERROR_NO_MORE_ITEMS)
{
break;
}
else if (returnValue == ERROR_MORE_DATA)
{
// Do stuff...
}
else if (returnValue != ERROR_SUCCESS)
{
throw new Win32Exception(returnValue);
}
dwIndex++;
}
}
I use windows 7 and VS 2010.
In my C# Winform program. I want to get the value in a line edit of an external .exe file.
I have get all the handle , but failed passing the correct parameters to SendMessage so I could not get the value of TEDIT.
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string
lpWindowName);
[DllImport("user32.dll")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr
hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError =
true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString,
int nMaxCount);
private static System.Diagnostics.Process p;
private void button3_Click_1(object sender, EventArgs e)
{
IntPtr intptr = FindWindow(null, "COLOR");
//IntPtr id = FindWindowEx(intptr, IntPtr.Zero, "TEdit", null);
IntPtr hWndTEDIT = FindWindowByIndex(intptr, 0);
IntPtr id = FindWindowEx(intptr, hWndTEDIT, "TEdit", null);
StringBuilder title = new StringBuilder(200);
// SendMessage(id, WM_GETTEXT, buffer, buffer_size);
// int length = SendMessage(id, WM_GETTEXT, 0, 0).ToInt32();
// StringBuilder builder = new StringBuilder(length);
// SendMessage(id, WM_GETTEXT, length, builder);
// LED_value = buffer.ToString();
LED_value = GetWindowText(id, title, 65536);
textBox2.AppendText(LED_value.ToString());
}
static IntPtr FindWindowByIndex(IntPtr hWndParent, int index)
{
if (index == 0)
return hWndParent;
else
{
int ct = 0;
IntPtr result = IntPtr.Zero;
do
{
result = FindWindowEx(hWndParent, result, "TEDIT", null);
if (result != IntPtr.Zero)
++ct;
}
while (ct < index && result != IntPtr.Zero);
return result;
}
}
Although the value in the TEDIT is 171B18. The LED_value is 0 after debugging.
enter image description here
I am trying to port the following C++ code:
BOOL SyskeyGetClassBytes(HKEY hKeyReg,LPSTR keyName,LPSTR valueName,LPBYTE classBytes) {
HKEY hKey,hSubKey;
DWORD dwDisposition=0,classSize;
BYTE classStr[16];
LONG ret;
BOOL isSuccess = FALSE;
ret = RegCreateKeyEx(hKeyReg,keyName,0,NULL,REG_OPTION_NON_VOLATILE,KEY_QUERY_VALUE,NULL,&hKey,&dwDisposition);
if(ret!=ERROR_SUCCESS)
return FALSE;
else if(dwDisposition!=REG_OPENED_EXISTING_KEY) {
RegCloseKey(hKey);
return FALSE;
}
else {
if(RegOpenKeyEx(hKey,valueName,0,KEY_READ,&hSubKey)==ERROR_SUCCESS) {
classSize = 8+1;
ret = RegQueryInfoKey(hSubKey,(LPTSTR)classStr,&classSize,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
if((ret==ERROR_SUCCESS)&&(classSize==8)) {
classBytes[0]= (HexDigitToByte(classStr[0]) << 4) | HexDigitToByte(classStr[1]);
classBytes[1]= (HexDigitToByte(classStr[2]) << 4) | HexDigitToByte(classStr[3]);
classBytes[2]= (HexDigitToByte(classStr[4]) << 4) | HexDigitToByte(classStr[5]);
classBytes[3]= (HexDigitToByte(classStr[6]) << 4) | HexDigitToByte(classStr[7]);
isSuccess = TRUE;
}
RegCloseKey(hSubKey);
}
RegCloseKey(hKey);
}
return isSuccess;
}
I spent like 5 hours trying to figure out my problem, with no success. I know for a fact that I am properly calling this method. My C# code is
unsafe static bool SyskeyGetClassBytes(RegistryHive hKeyReg, string keyName, string valueName, byte* classBytes)
{
UIntPtr hSubKey;
UIntPtr hKey;
RegResult tmp; ;
uint classSize;
StringBuilder classStr = new StringBuilder();
int ret;
bool isSuccess = false;
ret = RegCreateKeyEx(hKeyReg, keyName, 0, null, RegOption.NonVolatile, RegSAM.QueryValue, UIntPtr.Zero, out hKey, out tmp);
if (ret != 0)
{
return false;
}
else if (tmp != RegResult.OpenedExistingKey)
{
return false;
}
else
{
int res = RegOpenKeyEx(hKey, valueName, 0, (int)RegSAM.Read, out hSubKey);
if (res == 0)
{
classSize = 8 + 1;
ret = RegQueryInfoKey(hSubKey, out classStr, ref classSize, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if ((classSize == 8))
{
classBytes[0] = (byte)((byte)(HexDigitToByte(classStr[0]) << (byte)4) | HexDigitToByte(classStr[1]));
classBytes[1] = (byte)((byte)(HexDigitToByte(classStr[2]) << (byte)4) | HexDigitToByte(classStr[3]));
classBytes[2] = (byte)((byte)(HexDigitToByte(classStr[4]) << (byte)4) | HexDigitToByte(classStr[5]));
classBytes[3] = (byte)((byte)(HexDigitToByte(classStr[6]) << (byte)4) | HexDigitToByte(classStr[7]));
isSuccess = true;
}
RegCloseKey(hSubKey);
}
else
{
return false;
}
RegCloseKey(hKey);
}
return isSuccess;
}
Its a little bit hard for me to debug, but eventually I determined that the problem is occurring at this line. Execution seems to halt afterwards.
ret = RegQueryInfoKey(hSubKey, out classStr, ref classSize, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
I know this is not a problem with permissions, as this C# program is running with admin perms AND as the local system account. The method that I need that the .Net APIs don't offer is RegQueryInfoKey. My P/Invoke signatures and types used are:
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public unsafe byte* lpSecurityDescriptor;
public int bInheritHandle;
}
[Flags]
public enum RegOption
{
NonVolatile = 0x0,
Volatile = 0x1,
CreateLink = 0x2,
BackupRestore = 0x4,
OpenLink = 0x8
}
[Flags]
public enum RegSAM
{
QueryValue = 0x0001,
SetValue = 0x0002,
CreateSubKey = 0x0004,
EnumerateSubKeys = 0x0008,
Notify = 0x0010,
CreateLink = 0x0020,
WOW64_32Key = 0x0200,
WOW64_64Key = 0x0100,
WOW64_Res = 0x0300,
Read = 0x00020019,
Write = 0x00020006,
Execute = 0x00020019,
AllAccess = 0x000f003f
}
public enum RegResult
{
CreatedNewKey = 0x00000001,
OpenedExistingKey = 0x00000002
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int RegOpenKeyEx(
UIntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
out UIntPtr hkResult);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int RegCloseKey(
UIntPtr hKey);
[DllImport("advapi32.dll", SetLastError = true)]
static extern int RegCreateKeyEx(
RegistryHive hKey,
string lpSubKey,
int Reserved,
string lpClass,
RegOption dwOptions,
RegSAM samDesired,
UIntPtr lpSecurityAttributes,
out UIntPtr phkResult,
out RegResult lpdwDisposition);
[DllImport("advapi32.dll", EntryPoint = "RegQueryInfoKey", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
extern private static int RegQueryInfoKey(
UIntPtr hkey,
out StringBuilder lpClass,
ref uint lpcbClass,
IntPtr lpReserved,
IntPtr lpcSubKeys,
IntPtr lpcbMaxSubKeyLen,
IntPtr lpcbMaxClassLen,
IntPtr lpcValues,
IntPtr lpcbMaxValueNameLen,
IntPtr lpcbMaxValueLen,
IntPtr lpcbSecurityDescriptor,
IntPtr lpftLastWriteTime);
The lpClass parameter is declared incorrectly. Pass the StringBuilder by value.
[DllImport("advapi32.dll")]
extern private static int RegQueryInfoKey(
UIntPtr hkey,
StringBuilder lpClass,
ref uint lpcbClass,
IntPtr lpReserved,
IntPtr lpcSubKeys,
IntPtr lpcbMaxSubKeyLen,
IntPtr lpcbMaxClassLen,
IntPtr lpcValues,
IntPtr lpcbMaxValueNameLen,
IntPtr lpcbMaxValueLen,
IntPtr lpcbSecurityDescriptor,
IntPtr lpftLastWriteTime
);
You also need to allocate the StringBuilder instance to have the desired capacity. So, allocate the StringBuilder like this:
StringBuilder classStr = new StringBuilder(255);//or whatever length you like
And then set classSize like this:
classSize = classStr.Capacity+1;
I removed the parameters to DllImport. Most are not necessary, and the SetLastError is incorrect.
There may be other issues with your code, but with these changes at least the call to RegQueryInfoKey will match your C++ code.
Try this signature for RegQueryInfoKey:
[DllImport("advapi32.dll", EntryPoint="RegQueryInfoKey", CallingConvention=CallingConvention.Winapi, SetLastError=true)]
extern private static int RegQueryInfoKey(
UIntPtr hkey,
out StringBuilder lpClass,
ref uint lpcbClass,
IntPtr lpReserved,
out uint lpcSubKeys,
out uint lpcbMaxSubKeyLen,
out uint lpcbMaxClassLen,
out uint lpcValues,
out uint lpcbMaxValueNameLen,
out uint lpcbMaxValueLen,
out uint lpcbSecurityDescriptor,
IntPtr lpftLastWriteTime);
You are not declaring them as out params and in the RegQueryInfoKey Win32 call they are _Out_opt_.
You need to initialize your StringBuilder with enough capacity to store a classSize number of characters.
classSize = 8 + 1;
classStr.Capacity = classSize;
ret = RegQueryInfoKey(hSubKey, out classStr, ref classSize, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
The marshaller will use the capacity set on the StringBuilder to send a buffer of the capacity size to the RegQueryInfoKey function. Without that you are probably corrupted memory.
See http://msdn.microsoft.com/en-us/library/s9ts558h.aspx#cpcondefaultmarshalingforstringsanchor3
I'm trying to use the RtlGetCompressionWorkSpaceSize and RtlCompressBuffer functions in a C# project.
Here is what I have so far:
class Program
{
const uint COMPRESSION_FORMAT_LZNT1 = 2;
const uint COMPRESSION_ENGINE_MAXIMUM = 0x100;
[DllImport("ntdll.dll")]
static extern uint RtlGetCompressionWorkSpaceSize(uint CompressionFormat, out uint pNeededBufferSize, out uint Unknown);
[DllImport("ntdll.dll")]
static extern uint RtlCompressBuffer(uint CompressionFormat, byte[] SourceBuffer, uint SourceBufferLength, out byte[] DestinationBuffer,
uint DestinationBufferLength, uint Unknown, out uint pDestinationSize, IntPtr WorkspaceBuffer);
static void Main(string[] args)
{
uint dwSize = 0;
uint dwRet = 0;
uint ret = RtlGetCompressionWorkSpaceSize(COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_MAXIMUM, out dwSize, out dwRet);
IntPtr pMem = Marshal.AllocHGlobal((int)dwSize);
byte[] buffer = new byte[1024];
byte[] outBuf = new byte[1024];
uint destSize = 0;
ret = RtlCompressBuffer(COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_MAXIMUM, buffer, 1024, out outBuf, 1024, 0, out destSize, pMem);
Console.Write(ret.ToString());
Console.Read();
}
}
RtlGetCompressionWorkSpaceSize works since it returns 0 (NT success code) but when I call RtlCompressBuffer I get a Memory Access Violation error.
EDIT: With help from David's answer I've fixed the issue and the correct code is below.
const ushort COMPRESSION_FORMAT_LZNT1 = 2;
const ushort COMPRESSION_ENGINE_MAXIMUM = 0x100;
[DllImport("ntdll.dll")]
static extern uint RtlGetCompressionWorkSpaceSize(ushort CompressionFormat, out uint pNeededBufferSize, out uint Unknown);
[DllImport("ntdll.dll")]
static extern uint RtlCompressBuffer(ushort CompressionFormat, byte[] SourceBuffer, int SourceBufferLength, byte[] DestinationBuffer,
int DestinationBufferLength, uint Unknown, out int pDestinationSize, IntPtr WorkspaceBuffer);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr LocalAlloc(int uFlags, IntPtr sizetdwBytes);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LocalFree(IntPtr hMem);
internal static byte[] Compress(byte[] buffer)
{
var outBuf = new byte[buffer.Length * 6];
uint dwSize = 0, dwRet = 0;
uint ret = RtlGetCompressionWorkSpaceSize(COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_MAXIMUM, out dwSize, out dwRet);
if (ret != 0)
{
return null;
}
int dstSize = 0;
IntPtr hWork = LocalAlloc(0, new IntPtr(dwSize));
ret = RtlCompressBuffer(COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_MAXIMUM, buffer,
buffer.Length, outBuf, outBuf.Length, 0, out dstSize, hWork);
if (ret != 0)
{
return null;
}
LocalFree(hWork);
Array.Resize(ref outBuf, dstSize);
return outBuf;
}
You are very nearly there. The problem is this part of your P/invoke for RtlCompressBuffer:
out byte[] DestinationBuffer
The default marshalling for byte[] is for the array contents to marshalled in both directions, from managed to unmanaged, and then back again when the function returns. The C definition of RtlCompressBuffer is annotated with __out but that means that the array contents are __out rather than the pointer being __out.
Change your P/invoke to
byte[] DestinationBuffer
and similarly in the call to RtlCompressBuffer change out outBuf to outBuf and you should be good to go.
Be warned that your code as it stands will return an status code of STATUS_BUFFER_ALL_ZEROS so don't be tricked into thinking that this non-zero return value indicates failure.
One final point, the first parameter to both P/invokes, CompressionFormat, should be declared as ushort.
I am being told by an exception that's being thrown in the last line, that I'm trying to read/write on protected memory. What am I doing wrong here? Thanks
int count = (int)WinApi.SendMessage(_chatHwnd, WinApi.LB_GETCOUNT, 0, 0);
Debug.WriteLine("count=" + count);
StringBuilder sb = new StringBuilder(count * 20);
for (int i = _lastReadPosition; i < count; i++) {
int len = (int)WinApi.SendMessage(_chatHwnd, WinApi.LB_GETTEXTLEN, i, 0);
IntPtr text = Marshal.AllocHGlobal(len);
byte[] itemText = new byte[len];
WinApi.SendMessage(_chatHwnd, WinApi.LB_GETTEXT, i, text.ToInt32());
Marshal.Copy(text, itemText, 0, len);
string s = System.Text.Encoding.UTF8.GetString(itemText);
sb.Append(s);
}
Debug.WriteLine("analise"); <- EXCEPTION THROWN HERE
From the msdn:
LB_GETTEXTLEN
The return value is the length of the string, in TCHARs, excluding the terminating null character. Under certain conditions, this value may actually be greater than the length of the text. For more information, see the following Remarks section.
LB_GETTEXT
A pointer to the buffer that will receive the string; it is type LPTSTR which is subsequently cast to an LPARAM. The buffer must have sufficient space for the string and a terminating null character. An LB_GETTEXTLEN message can be sent before the LB_GETTEXT message to retrieve the length, in TCHARs, of the string.
You need to provide space for one additional null TCHAR. However I see several other problems in your code:
Your system is WinNT? Then lb_gettextlen returns length in TCHAR and on NT systems one TCHAR is two bytes long
I see AllocHGlobal, but I do not see FreeHGlobal. Memory leak?
Why you convert byte array to string using UTF8 encoding? You need to use Unicode.
Your SendMessage interface potentially dangerous, because it does not expect x64 pointers.
Update: In general your code must look like this:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder lParam);
private void Form1_Shown(object sender, EventArgs e)
{
int count = (int)SendMessage(_chatHwnd, WinApi.LB_GETCOUNT, IntPtr.Zero, IntPtr.Zero);
StringBuilder sb = new StringBuilder(count * 20);
for (int i = _lastReadPosition; i < count; i++)
{
int len = (int)SendMessage(_chatHwnd, WinApi.LB_GETTEXTLEN, (IntPtr)i, IntPtr.Zero);
StringBuilder LineBuilder = new StringBuilder(len + 1);
SendMessage(_chatHwnd, WinApi.LB_GETTEXT, (IntPtr)i, LineBuilder);
sb.Append(LineBuilder.ToString());
}
}