WM_DEVICECHANGE strange issue

Peter Volz 1,295 Reputation points
2024-02-22T06:06:56.0966667+00:00

Hello experts Here I found how to listen to disk inserted or new drive added events: https://learn.microsoft.com/en-us/answers/questions/1555337/optical-drive-disc-inserted-event?source=docs And this is my code:

<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)>
Protected Overrides Sub WndProc(ByRef m As Message)
    If Button1.Enabled = False Then Exit Sub
    If m.Msg = WM_DEVICECHANGE AndAlso m.WParam.ToInt32() = DBT_DEVICEARRIVAL OrElse m.WParam.ToInt32() = DBT_DEVICEREMOVECOMPLETE OrElse m.WParam.ToInt32() = DBT_DEVNODES_CHANGED Then
        If m.LParam <> Nothing AndAlso Marshal.ReadInt32(m.LParam, 4) = DBT_DEVTYP_VOLUME Then RefreshButton_Click(Me, Nothing)
    End If
    MyBase.WndProc(m)
End Sub

But however, this line:

If Button1.Enabled = False Then Exit Sub

Will cause the form stop working normally and strange behavior, almost hang! Removing that single line will make it work as expected! Am I doing it correctly? And is this method safe at all or forget it? One more thing is that is it safe to use it on multiple forms? Thanks :)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,842 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,714 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 31,011 Reputation points Microsoft Vendor
    2024-02-22T07:21:20.0633333+00:00

    Hi @Peter Volz ,

    When Button1.Enabled = False, the code will exit Sub WndProc immediately when it reaches this line.

    If you don't have a mandatory requirement for the state of Button1 in this method, you can delete this line.

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.