我创建了一个捕获桌面屏幕截图的应用程序。它与我在表单中使用的按钮非常有效。但现在我想让这个东西自动使用定时器,但每当我尝试运行程序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
提前致谢....
答案 0 :(得分:1)
我认为问题出在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下进行调试,以查看抛出异常的位置。