Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by razorblade2k · Jun 22, 2014 at 10:04 PM · system.iomessageswindows-form

Receiving Windows messages in Unity

I need to react to the event of a USB device being unplugged and plugged in. I found a solution for Windows Forms reacting to the WM_DEVICECHANGE message sent by the system. In plain C# it works really well, but I can't get it to work with unity. Are there any ideas?

Following is the code I used for testing with Windows Forms:

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;
 using System.Runtime.InteropServices;
 
 namespace HardwareServiceTest
 {
 internal static class UsbNotification
     {
         public const int DbtDevicearrival = 0x8000; // system detected a new device        
         public const int DbtDeviceremovecomplete = 0x8004; // device is gone      
         public const int WmDevicechange = 0x0219; // device change event
         public const int DbtConfigChanged = 0x0018;
         public const int DbtDeviceSpecific = 0x8005;
         public const int DbtDevnodesChanged = 0x0007;
         private const int DbtDevtypDeviceinterface = 5;
         private static readonly Guid GuidDevinterfaceUSBDevice = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); // USB 
         private static IntPtr notificationHandle;
         
         /// <summary>
         /// Registers a window to receive notifications when USB devices are plugged or unplugged.
         /// </summary>
         /// <param name="windowHandle">Handle to the window receiving notifications.</param>
         public static void RegisterUsbDeviceNotification(IntPtr windowHandle)
         {
             DevBroadcastDeviceinterface dbi = new DevBroadcastDeviceinterface
             {
                 DeviceType = DbtDevtypDeviceinterface,
                 Reserved = 0,
                 ClassGuid = GuidDevinterfaceUSBDevice,
                 Name = 0
             };
 
             dbi.Size = Marshal.SizeOf(dbi);
             IntPtr buffer = Marshal.AllocHGlobal(dbi.Size);
             Marshal.StructureToPtr(dbi, buffer, true);
 
             notificationHandle = RegisterDeviceNotification(windowHandle, buffer, 0);
         }
 
         /// <summary>
         /// Unregisters the window for USB device notifications
         /// </summary>
         public static void UnregisterUsbDeviceNotification()
         {
             UnregisterDeviceNotification(notificationHandle);
         }
 
         [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
         private static extern IntPtr RegisterDeviceNotification(IntPtr recipient, IntPtr notificationFilter, int flags);
 
         [DllImport("user32.dll")]
         private static extern bool UnregisterDeviceNotification(IntPtr handle);
 
         [StructLayout(LayoutKind.Sequential)]
         private struct DevBroadcastDeviceinterface
         {
             internal int Size;
             internal int DeviceType;
             internal int Reserved;
             internal Guid ClassGuid;
             internal short Name;
         }
     }
     
 
     public partial class Form1 : Form
     {
         [DllImport("user32.dll", SetLastError = true)]
         static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
         
         public Form1()
         {
             InitializeComponent();
             UsbNotification.RegisterUsbDeviceNotification(this.Handle);
 
         }
         protected override void WndProc(ref Message m)
         {
             base.WndProc(ref m);
             if (m.Msg == UsbNotification.WmDevicechange)
             {
                 switch ((int)m.WParam)
                 {
                     case UsbNotification.DbtDeviceremovecomplete:
                         Usb_DeviceRemoved(); // this is where you do your magic
                         break;
                     case UsbNotification.DbtDevicearrival:
                         Usb_DeviceAdded(); // this is where you do your magic
                         break;
                     case UsbNotification.DbtConfigChanged:
                         Usb_ConfigChanged();
                         break;
                     case UsbNotification.DbtDevnodesChanged:
                         Usb_NodesChanged();
                         break;
                 }
             }
         }
         public void Usb_DeviceRemoved()
         {
             label1.Text = "A USB device was removed!";
         }
 
         public void Usb_DeviceAdded()
         {
             label1.Text = "A USB device was added!";
         }
         public void Usb_ConfigChanged()
         {
             label1.Text = "Config changed!";
         }
         public void Usb_NodesChanged()
         {
             label1.Text = "Nodes changed!";
         }
     }
    
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Dreamora · Jun 22, 2014 at 10:09 PM

Solutions that work with Standard C# won't work with Unity commonly, as they nearly alwys rely on the presence of Windows Forms which don't exist in Unity or Mono in general (they are MS.NET on Windows only) or assume / require that your code has access to the event handling loop which unluckily is not the case.

To my knowledge, you can not even hook into the default event pipeline as Unity does not expose it.

What we've done this far in such a situation is having a 2nd process that intercepts relevant events and forwards them, through TCP in our case (you could use pipes, UDP, TCP), so we can react to the events as required.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Player lives script help 1 Answer

Animation spins wildly after completed 0 Answers

hide object start script 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges