在我的Visual Basic程序中提供帮助

时间:2013-10-19 10:21:06

标签: vb.net

我的Visual Basic.net代码有问题

我正在制作一种能够记录按键并拍摄屏幕截图的“儿童监控软件”,但我不知道如何在已经存在的情况下创建一个新的.bmp文件。

 Try
        'the working area excludes all docked toolbars like taskbar, etc.
        Dim currentScreen = Screen.FromHandle(Me.Handle).WorkingArea

        'create a bitmap of the working area
        Using bmp As New Bitmap(currentScreen.Width, currentScreen.Height)

            'copy the screen to the image
            Using g = Graphics.FromImage(bmp)
                g.CopyFromScreen(New Point(0, 0), New Point(0, 0), currentScreen.Size)
            End Using

            'save the image
             'look for the file
            If IO.File.Exists(save1.Text) Then
                 'if exsist then add (2) to the filename
                bmp.Save(Save1.text + "(2)" + ".bmp")
              'done
            End If
            bmp.Save(Save1.Text)

        End Using
    Catch ex As Exception
    End Try


End Sub

正如您所看到的,程序会检查bmp文件是否已存在,如果是,程序将生成新的bmp文件。例如:如果file(whatever.bmp)存在,那么它不会覆盖它,而是在文件名exmp:(whatever(2).bmp)中添加“(2)”。

所以问题是我不想为这个函数生成几十行代码,我正在寻找一种自动方式来添加(2),(3),(4)或其他任何文件名如果它已经存在以防止覆盖。

抱歉我的英文不好:D

-Matt

3 个答案:

答案 0 :(得分:0)

首先在类声明中初始化一个存储图片索引的变量:

Private picIndex As Long = 0

然后你可以使用Threading.Interlocked.Increment增加变量号:

bmp.Save(String.Format("{0} {1}.bmp", _
                       Save1.text, _
                       Threading.Interlocked.Increment(picIndex)))

如果您正在尝试编写通用程序,那么您将考虑在变量内添加Static

Public shared Sub MakeScreenshot(...)
    ...
    Static picIndex As Long = 0
    ...
End Sub

答案 1 :(得分:0)

作为一个简单的解决方案,您可以增加数字并检查文件是否存在。如果没有 - 保存它。

For i As Integer = 0 To Int32.MaxValue - 1
    Dim name As String = Save1.text + "(" + i + ").bmp"
    If Not File.Exists(name) Then
        bmp.Save(name)
            Exit For
    End If
Next

答案 2 :(得分:0)

Dim counter as integer
counter = My.Computer.FileSystem.GetFiles("your image folder path")
bmp.Save(Save1.text & "(" & counter & ")" & ".bmp")
相关问题