0

我的 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 文件。例如:如果文件 (whatever.bmp) 存在,则不会覆盖它,而是在文件名 exmp: (whatever(2).bmp) 中添加“(2)”。

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

对不起我的英语不好:D

-马特

4

3 回答 3

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
于 2013-10-19T10:36:27.103 回答
0
Dim counter as integer
counter = My.Computer.FileSystem.GetFiles("your image folder path")
bmp.Save(Save1.text & "(" & counter & ")" & ".bmp")
于 2013-10-19T10:45:06.713 回答
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
于 2013-10-19T10:27:25.317 回答