C#UpdateResource函数失败

时间:2012-04-11 14:10:31

标签: c# resources

我正在用C#编写一个简单的应用程序,它允许将资源添加到我选择的.EXE文件中。 问题是对UpdateResource函数的调用失败,错误6,根据MSDN是InvalidHandle(尽管看起来对BeginUpdateResource的调用是成功的)(代码被复制并粘贴到更大的文件中,所以如果有些{缺乏,不关心,代码编译,但不能按预期工作)

public partial class Form1 : Form
{
    [DllImport("kernel32.dll", SetLastError=true)] 
    static extern bool UpdateResource(IntPtr hUpdate, string lpType, string lpName, ushort wLanguage, IntPtr lpData, uint cbData);

    [DllImport("kernel32.dll",SetLastError=true)]
    static extern IntPtr BeginUpdateResource(string pFileName, [MarshalAs(UnmanagedType.Bool)]bool bDeleteExistingResources);

    [DllImport("kernel32.dll",SetLastError=true)]
    static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);

    static unsafe void  SetRes(string path)
    {
        IntPtr beginPointer = BeginUpdateResource(path, false);

        if (beginPointer != null)
        {
            MessageBox.Show("Begin works");//This is shown

            ushort id = (ushort)Language.MakeLanguageID();
            string newMessage = "hello world!";
            Byte[] bytes = new ASCIIEncoding().GetBytes(newMessage);
            GCHandle bHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            IntPtr ptr = bHandle.AddrOfPinnedObject();

            bool update = UpdateResource(beginPointer,"FILE", "Test", id,ptr, (uint)bytes.Length);

            if (update == true)
            {
                MessageBox.Show("Update");
                EndUpdateResource(beginPointer, false);

            }
            else
            {
                MessageBox.Show(Marshal.GetLastWin32Error().ToString()); //It gives error 6
            }
        }
    }

0 个答案:

没有答案