1

デスクトップ画面のスクリーンショットをキャプチャするアプリケーションを作成しました。フォームで使用したボタンで非常にうまく機能します。しかし、今はタイマーを使用して自動的に機能させたいと思っていますが、プログラムを実行しようとするたびに、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

前もって感謝します....

4

1 に答える 1

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 でデバッグできるはずです。

于 2013-05-09T13:59:04.353 に答える