对象引用错误 - Struct @ WM_DEVICECHANGE

时间:2012-10-29 18:37:52

标签: c#

我几乎准备好了我的程序,我认为它运行得非常顺利。我刚刚意识到,在检查usb到达时,很多“对象引用未设置为对象的实例”。在阅读应该与winmsg一起到达的结构时,我被抛到脑后。在插入和拔出USB时我得到3-4个Nullreference错误。

我做错了什么?

public partial class Form1 : Form
{
    private const int WM_DEVICECHANGE = 0x0219;
    private const int DBT_DEVICEARRIVAL = 0x8000;
    private const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    private const int DBT_DEVTYPVOLUME = 0x00000002;

    public Form1()
    {
        InitializeComponent();
    }

    protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            try
            {
                Debug.WriteLine("trying");
                DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));

                if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
                {
                    Debug.WriteLine("usb in");
                    //NewStickArrived(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
                }
                if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
                {
                    Debug.WriteLine("usb out");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

}

}

您还需要关注以尝试此示例:

using System.Diagnostics;
using System.Runtime.InteropServices;

我想它可能是1.我对结构做错了,因为我还不太了解它们,或者2.有时候这是“Marshal.PtrToStructure(m.LParam [。 ..]“不适合结构......

由于

0 个答案:

没有答案