Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

how to trigger event when a com device is connected in c#

/*
Headers to be used:-
using System;
using System.Runtime.InteropServices;

*/


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;
        }
    }
}   

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      
    private const int DbtDevtypDeviceinterface = 5;
    private static readonly Guid GuidDevinterfaceUSBDevice = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); // USB devices
    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;
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: c# execute run control panel 
Csharp :: remove lines from textfile 
Csharp :: upcasting and downcasting in c# 
Csharp :: method declaration in c# 
Csharp :: c# extension method in non static class 
Csharp :: Compiling C# Example 
Csharp :: date format full month name c# selenium 
Csharp :: how to declare two int variables in only one line c# 
Csharp :: cache.TryGetValue in MemoryCache c# .net 
Csharp :: cannot access file being used by another process create file 
Csharp :: linq pick random element 
Csharp :: using autofac with automapper .net 6 with dependency injection 
Csharp :: convert array to datatable c# 
Csharp :: rest api in c# 
Csharp :: c# listview 
Csharp :: how to add a componet to a gameobject throgh code unity 
Csharp :: c# loop array back 
Csharp :: how to delete file in c# 
Csharp :: c# application exit 
Csharp :: c# movement script 
Csharp :: width="331" height="331" 
Csharp :: razor: show editable list 
Html :: html yuan symbol 
Html :: td align top 
Html :: free video url for testing 
Html :: how to run vscode as root 
Html :: fa icons profile 
Html :: bootstrap two buttons side by side with space 
Html :: youtube autoplay video 
Html :: svg circle 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =