VB.NET 中的屏幕截图程序

2023-12-14

我创建了一个捕获桌面屏幕截图的应用程序。它与我在表单中使用的按钮配合得很好。但现在我想使用计时器让这个东西自动工作,但是每当我尝试运行程序时NullReferenceException发生任何人都可以告诉我这里出了什么问题吗?

TimerCapture interval=5

TimerSave interval=6

下面的代码可以告诉你这个场景:

Public Class Form1


    Private Sub timerCapture_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerCapture.Tick
        Dim bounds As Rectangle
        Dim screenshot As System.Drawing.Bitmap
        Dim graph As Graphics
        bounds = Screen.PrimaryScreen.Bounds
        screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
        graph = Graphics.FromImage(screenshot)
        graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
        PictureBox1.Image = screenshot
    End Sub




    Private Sub timerSave_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerSave.Tick
        Me.PictureBox1.Image.Save("d:\\capture.bmp")

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' Me.WindowState = FormWindowState.Minimized

        'Me.ShowInTaskbar = False

    End Sub

    Private Sub timerClose_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerClose.Tick
        Me.Close()

    End Sub

    Private Sub capture_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles capture_btn.Click
        Dim bounds As Rectangle
        Dim screenshot As System.Drawing.Bitmap
        Dim graph As Graphics
        bounds = Screen.PrimaryScreen.Bounds
        screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
        graph = Graphics.FromImage(screenshot)
        graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
        PictureBox1.Image = screenshot
    End Sub

    Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
        Me.PictureBox1.Image.Save("d:\\capture.bmp")
    End Sub
End Class

提前致谢....


我认为问题出在timerSave_Tick中,如果由于某种原因你还没有在timerCapture_Tick中重视Me.PictureBox1.Image,它会在尝试访问PictureBox1.Image时抛出NullReferenceException。

尝试用这样的方式修改它:

Private Sub timerSave_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerSave.Tick
    If(Me.PictureBox1.Image IsNot Nothing) Then
        Me.PictureBox1.Image.Save("d:\\capture.bmp")
    End If
End Sub

无论如何,您应该能够在 Visual Studio 下进行调试,以查看抛出异常的位置。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VB.NET 中的屏幕截图程序 的相关文章

随机推荐