我在这里分别有两个代码可以工作但是当我把它放在一起时我得到错误"跨线程操作无效"。我试图在网上搜索如何解决这个问题,我只是不知道如何在我的代码中应用它。
Cross-Thread operation not valid VB.NET
代码1用于屏幕截图我的PANEL控件。
Private Sub CaptureSHOT(ctrl As Control, fileName As String)
Dim bounds As Rectangle = ctrl.Bounds
Dim pt As Point = ctrl.PointToScreen(bounds.Location)
Dim bitmap As New Bitmap(bounds.Width, bounds.Height)
Using g As Graphics = Graphics.FromImage(bitmap)
g.CopyFromScreen(New Point(pt.X - ctrl.Location.X, pt.Y - ctrl.Location.Y), Point.Empty, bounds.Size)
End Using
bitmap.Save(fileName, ImageFormat.Png)
End Sub
CODE 2用于呼叫我的" CaptureShot" FORM加载时通过计时器发挥作用。
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
Dim tmr As New System.Timers.Timer()
tmr.Interval = 2000
tmr.Enabled = True
tmr.Start()
AddHandler tmr.Elapsed, AddressOf OnTimedEvent
End Sub
Private Delegate Sub CloseFormCallback()
Private Sub CloseForm()
If InvokeRequired Then
Dim d As New CloseFormCallback(AddressOf CloseForm)
Invoke(d, Nothing)
Else
Close()
End If
End Sub
Private Sub OnTimedEvent(ByVal sender As Object, ByVal e As ElapsedEventArgs)
CaptureSHOT(Panel1, "D:\SC\" & erk & ".png")
CloseForm()
End Sub
答案 0 :(得分:2)
Geez今天你们都充满敌意哈哈开玩笑,感谢Enigmativity和varocarbas严格的演讲,我注意到我已经为我的CloseFormCallback()提供了一个“私人代表子”,并且我一直收到错误,因为我正在添加另一个“私人”委托子“为我的”CaptureShot“功能。现在我只需将“CaptureSHOT(Panel1,”D:\ SC \“& erk&”.png“)”添加到我的私人代表Sub CloseFormCallback()。它有效!
Private Delegate Sub CloseFormCallback()
Private Sub CloseForm()
If InvokeRequired Then
Dim d As New CloseFormCallback(AddressOf CloseForm)
Invoke(d, Nothing)
Else
CaptureSHOT(Panel1, "D:\SC\" & erk & ".png")
Close()
End If
End Sub