Deathhound
Deathhound

Reputation: 67

VB Conflicting Code

I'm making a program in Microsoft Visual Studio 2014 to lock my computer when it no longer detects my USB.

Here is my current code:

    Imports System.IO

    Public Class Form1

        Function USB()
            Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
            Dim list As New List(Of String)
            For Each d As DriveInfo In allDrives
                If d.IsReady Then
                    list.Add(d.VolumeLabel)
                    If Not (list.Contains("NERD STICK")) Then
                        Label1.Text = "False"
                        Form2.Show()
                        Me.BackColor = Color.Red
                    Else
                        Label1.Text = "True"
                        Form2.Hide()
                        Me.BackColor = Color.Green
                    End If
                End If
            Next
        End Function

        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Timer1.Start()
        End Sub

        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            USB()
        End Sub
    End Class

Form1 is just a simple test to see the status of the USB (label true or false, background green or red) and form2 is what is going to show when the computer is "locked" and the USB is out.

Although it is somehow confused and form2 keeps appearing and disappearing when the timer ticks and the function USB is run again.

If anyone could help sort this mess out I'd be very grateful!

Upvotes: 1

Views: 64

Answers (1)

Steve
Steve

Reputation: 216293

You could rewrite your USB function and take advantage of the LINQ Count operator

Sub USB()
    Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
    Dim cnt = allDrives.Count(Function(x) x.IsReady AndAlso x.VolumeLabel.Contains("NERD STICK"))
    if cnt = 0 then
        l.Text = "False"
        f.Show()
        f.BackColor = Color.Red
    else
        l.Text = "True"
        f.Hide()
        f.BackColor = Color.Green
    End if
End Sub

This avoid the continuos call to Show-Hide for every drive checked in your current code.
(Albeit I am not sure how this cause flicker)

As a side note, I suppose that you are aware that, if this is a simple protection mechanism, it is easy to circumvent.

Upvotes: 1

Related Questions