0

FIXED WITH: if (m.LParam != null) { // All code in } I have the following script detecting the insertion and removal of a USB flash drive, i tested the program outside of visual studio and it gave me a nulreference exeption error, System.NullReferenceException: the object reference not set to an instance of an object.

The line the error gave me was

      DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));

and the entire part of code is:

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            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))
            {
              //  MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
                notifyIcon1.BalloonTipText = "USB Drive with letter: " + DriveMaskToLetter(vol.dbcv_unitmask).ToString() + "Detected and will now copy. Press" + "insertuserselectedhotkeyasastringhere" + " To cancel";
                notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
                notifyIcon1.BalloonTipTitle = "USBAutoSave";
                notifyIcon1.ShowBalloonTip(3000);
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        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;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }
marceltje
  • 107
  • 1
  • 9

0 Answers0