Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created August 22, 2016 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/2b6759c7eeca1a28789e7f95c07654b1 to your computer and use it in GitHub Desktop.
Save wolf99/2b6759c7eeca1a28789e7f95c07654b1 to your computer and use it in GitHub Desktop.
Extension to add strings to a VB.NET ListBox for output or console logging.
'Usage: ListBox1.AddLogLine("Log this!")
Imports System.Runtime.CompilerServices
Module FormExtensions
Delegate Sub UpdateLog(lb As ListBox, line As String)
<Extension()>
Public Sub AddLogLine(lb As ListBox, line As String)
If (lb.InvokeRequired) Then 'Invoke from the GUI thread if called from a different one
lb.Invoke(New UpdateLog(AddressOf AddLogLine), lb, line)
Else
lb.Items.Add(line) 'Add the given line
If lb.Items.Count > 100 Then 'Remove old lines once the line limit is exceeded
lb.Items.RemoveAt(0)
End If
lb.SelectedIndex = lb.Items.Count - 1 'Ensure the latest line is shown
lb.ClearSelected()
End If
End Sub
End Module
'The following may also be useful to allow Ctrl + C copying from the listbox
'- First set ListBox1.SelectionMode = SelectionMode.MultiExtended
' Private Sub ListBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) _
' Handles ListBox1.KeyDown
'
' If e.Control AndAlso e.KeyCode = Keys.C Then 'Detect Ctrl + C shortcut key combo
' Dim Buffer As New System.Text.StringBuilder 'Create a string by concatenating all selected list items
' For Each item As Object In ListBox1.SelectedItems
' Buffer.AppendLine(item.ToString)
' Next
' If Buffer.Length > 0 Then
' Clipboard.SetText(Buffer.ToString) 'Save the created string to the users clipboard
' End If
' End If
' End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment