Text Output Functions (Colorizing for Console)

   Function funWriteTextColorful(sText As String) As Boolean

        Dim aColors = {ConsoleColor.Red, ConsoleColor.Magenta, ConsoleColor.Yellow, ConsoleColor.Green, ConsoleColor.Cyan, ConsoleColor.White}

        Static iColorNum As Integer

        'ReD,orange,yell,gre,blu,ind,vio

        Dim oldColor As ConsoleColor = Console.ForegroundColor

        For x As Integer = 0 To sText.Length - 1

            Dim ch As Char = Strings.Mid(sText, x + 1, 1)

            Console.ForegroundColor = aColors(iColorNum)

            Console.Write(ch)

            If Not Char.IsWhiteSpace(ch) Then iColorNum += 1

            If iColorNum Mod UBound(aColors) = 0 Then iColorNum = 0

        Next

        Console.ForegroundColor = oldColor

    End Function



    Function funWriteWordinColor(sText As String, cfFontColor As ConsoleColor)

        Dim oldColor As ConsoleColor = Console.ForegroundColor

        Console.ForegroundColor = cfFontColor

        Console.Write(sText)

        Console.ForegroundColor = oldColor

    End Function

Get Icon for Extension


'https://www.vbforums.com/showthread.php?702801-RESOLVED-Getting-Icon-for-a-particular-extension
Imports System.Runtime.InteropServices

Public Class Form1
    ' example...
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        ' Get Small Icon for PDF file types
        PictureBox1.Image = GetFileIcon(".PDF")
        ' Get Large Icon for RAR file type
        PictureBox2.Image = GetFileIcon(".rar", IconSize.SHGFI_LARGEICON)
    End Sub

    Private Const MAX_PATH As Int32 = 260
    Private Const SHGFI_ICON As Int32 = &H100
    Private Const SHGFI_USEFILEATTRIBUTES As Int32 = &H10
    Private Const FILE_ATTRIBUTE_NORMAL As Int32 = &H80

    Private Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Int32
        Public dwAttributes As Int32
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=MAX_PATH)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

    Private Enum IconSize
        SHGFI_LARGEICON = 0
        SHGFI_SMALLICON = 1
    End Enum

    <DllImport("shell32.dll", CharSet:=CharSet.Auto)> _
    Private Shared Function SHGetFileInfo( _
                ByVal pszPath As String, _
                ByVal dwFileAttributes As Int32, _
                ByRef psfi As SHFILEINFO, _
                ByVal cbFileInfo As Int32, _
                ByVal uFlags As Int32) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function DestroyIcon(ByVal hIcon As IntPtr) As Boolean
    End Function

   ' get associated icon (as bitmap).
    Private Function GetFileIcon(ByVal fileExt As String, Optional ByVal ICOsize As IconSize = IconSize.SHGFI_SMALLICON) As Bitmap
        Dim shinfo As New SHFILEINFO
        shinfo.szDisplayName = New String(Chr(0), MAX_PATH)
        shinfo.szTypeName = New String(Chr(0), 80)
        SHGetFileInfo(fileExt, FILE_ATTRIBUTE_NORMAL, shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON Or ICOsize Or SHGFI_USEFILEATTRIBUTES)
        Dim bmp As Bitmap = System.Drawing.Icon.FromHandle(shinfo.hIcon).ToBitmap
        DestroyIcon(shinfo.hIcon) ' must destroy icon to avoid GDI leak!
        Return bmp ' return icon as a bitmap
    End Function

End Class

Convert to RGB


Public Function ConvertToRbg(ByVal HexColor As String) As Color
    Dim Red As String
    Dim Green As String
    Dim Blue As String
    HexColor = Replace(HexColor, "#", "")
    Red = Val("&H" & Mid(HexColor, 1, 2))
    Green = Val("&H" & Mid(HexColor, 3, 2))
    Blue = Val("&H" & Mid(HexColor, 5, 2))
    Return Color.FromArgb(Red, Green, Blue)
End Function

Hex to Color

Public Shared Function HexToColor(ByVal hexColor As String) As Color
    If hexColor.IndexOf("#"c) <> -1 Then
        hexColor = hexColor.Replace("#", "")
    End If
    Dim red As Integer = 0
    Dim green As Integer = 0
    Dim blue As Integer = 0
    If hexColor.Length = 6 Then
        red = Integer.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier)
        green = Integer.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier)
        blue = Integer.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier)
    ElseIf hexColor.Length = 3 Then
        red = Integer.Parse(hexColor(0).ToString() + hexColor(0).ToString(), NumberStyles.AllowHexSpecifier)
        green = Integer.Parse(hexColor(1).ToString() + hexColor(1).ToString(), NumberStyles.AllowHexSpecifier)
        blue = Integer.Parse(hexColor(2).ToString() + hexColor(2).ToString(), NumberStyles.AllowHexSpecifier)
    End If
    Return Color.FromArgb(red, green, blue)
End Function

Text Output  (spacing)

   Function funFormatColumns(sString As String, iCount As Integer, blnFormatAddSpace As Boolean)

        If iCount > Len(sString) Then

            Dim iDiff As Integer = iCount - Len(sString)

            funFormatColumns = sString & Space(iDiff)

        Else

            funFormatColumns = Left(sString, iCount)

        End If

        If blnFormatAddSpace Then funFormatColumns = funFormatColumns & " "

    End Function


Create Text as an Image on the fly and add to control

New Way

Function createTextImage(text As String, oColor As Color, Optional width As Integer = 32, Optional height As Integer = 12) As Bitmap ' As String

        Dim bitmap As New Bitmap(1, 1)
        Dim font As Font

        Try
            font = New Font(pfc.Families(0), height, FontStyle.Regular, GraphicsUnit.Pixel)
        Catch
            font = New Font("arial", 12, FontStyle.Regular, GraphicsUnit.Pixel)
        End Try

        Dim graphics As Graphics = Graphics.FromImage(bitmap)
        bitmap = New Bitmap(bitmap, New Size(width, height + 5))
        graphics = Graphics.FromImage(bitmap)
        graphics.SmoothingMode = SmoothingMode.AntiAlias
        graphics.TextRenderingHint = TextRenderingHint.AntiAlias
        graphics.DrawString(text, font, New SolidBrush(oColor), 0, 0)

        graphics.Flush()
        graphics.Dispose()

        Return bitmap

End Function

 

Old way

    Function createTextImage(text As String, oColor As Color) As String

        'Dim text As String = txtText.Text.Trim()

        Dim bitmap As New Bitmap(1, 1)

        Dim font As New Font("Arial", 25, FontStyle.Bold, GraphicsUnit.Pixel)

        Dim graphics As Graphics = Graphics.FromImage(bitmap)

        Dim width As Integer = CInt(graphics.MeasureString(text, font).Width)

        Dim height As Integer = CInt(graphics.MeasureString(text, font).Height)

        bitmap = New Bitmap(bitmap, New Size(width, height))

        graphics = Graphics.FromImage(bitmap)

        graphics.Clear(Color.White)

        graphics.SmoothingMode = SmoothingMode.AntiAlias

        graphics.TextRenderingHint = TextRenderingHint.AntiAlias

        'graphics.DrawString(text, font, New SolidBrush(Color.FromArgb(255, 0, 0)), 0, 0)

        graphics.DrawString(text, font, New SolidBrush(oColor), 0, 0)

        graphics.Flush()

        graphics.Dispose()

        Dim fileName As String = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) & ".jpg"

        bitmap.Save(Environment.ExpandEnvironmentVariables("%TEMP%") & "\" & fileName, ImageFormat.Jpeg)

        'imgText.ImageUrl = "~/images/" & fileName

        'imgText.Visible = True

        Return Environment.ExpandEnvironmentVariables("%TEMP%") & "\" & fileName

    End Function

https://www.aspsnippets.com/Articles/Create-Text-Image-on-the-fly-with-ASPNet.aspx

ToIcon function icon

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToIcon(img As Bitmap, makeTransparent As Boolean, colorToMakeTransparent As Color) As Icon
    If makeTransparent Then
        img.MakeTransparent(colorToMakeTransparent)
    End If
    Dim iconHandle = img.GetHicon()
    Return Icon.FromHandle(iconHandle)
End Function

 

Display and render an SVG file

by using a WebBrowser control, as PictureBox cannot do it

WebBrowser1.Navigate(New Uri(jArrayLocation("country_flag")))

    Dim wbWidth As Integer
    Dim wbHeight As Integer
    Dim pswaHeight As Object
    Dim pswaWidth As Object
    Dim pswaHeightInt As Integer
    Dim pswaWidthInt As Integer

    Private Enum Exec
        OLECMDID_OPTICAL_ZOOM = 63
    End Enum

    Private Enum execOpt
        OLECMDEXECOPT_DODEFAULT = 0
        OLECMDEXECOPT_PROMPTUSER = 1
        OLECMDEXECOPT_DONTPROMPTUSER = 2
        OLECMDEXECOPT_SHOWHELP = 3
    End Enum


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        pswaHeight = WebBrowser1.Height ' Screen.PrimaryScreen.WorkingArea.Height
        pswaWidth = WebBrowser1.Width ' Screen.PrimaryScreen.WorkingArea.Width
        pswaHeightInt = CInt(pswaHeight)
        pswaWidthInt = CInt(pswaWidth)
    End Sub

Load Icons from a file (dll, exe, program, etc)

    Private Sub LoadIcons(ByVal FilePath As String)
        'Clear the list view and image lists
        IconListView.Clear()
        SmallIcons.Images.Clear()
        LargeIcons.Images.Clear()
        Dim NumberOfIcons As UInteger = 0
        'Find out how many icons are in the selected file by calling the API and passing in -1 as the Index
        NumberOfIcons = WindowsApi.ExtractIconExW(FilePath, -1, Nothing, Nothing, 0)
        If NumberOfIcons = 0 Then
            MessageBox.Show("No icons found in file", "No Icons Found", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Else
            'If there are more than 0 icons we loop through the icons in the file
            For i As Integer = 0 To CInt(NumberOfIcons) - 1
                Dim SmallIconHandle As IntPtr = Nothing
                Dim LargeIconHandle As IntPtr = Nothing
                'Call the API to extract the current icon that we are on in the loop
                WindowsApi.ExtractIconExW(FilePath, i, LargeIconHandle, SmallIconHandle, 1)
                'Add the large version of the extracted icon to our large image list
                LargeIcons.Images.Add(i.ToString, Drawing.Icon.FromHandle(LargeIconHandle))
                'Add the small version of the extracted icon to our small image list
                SmallIcons.Images.Add(i.ToString, Drawing.Icon.FromHandle(SmallIconHandle))
                'Create a new listviewitem for this icon, specifying the index number as the image key
                Dim LvItem As New ListViewItem(i.ToString, i.ToString)
                'Add the item to the listview
                IconListView.Items.Add(LvItem)
                'Clean up
                WindowsApi.DestroyIcon(SmallIconHandle)
                WindowsApi.DestroyIcon(LargeIconHandle)
            Next
        End If
    End Sub

    Public Class WindowsApi

    ''' <summary>
    ''' Extracts an icon from a specified exe, dll or icon file. Call DestroyIcon on handles once finished.
    ''' </summary>
    ''' <param name="lpszFile">The file to extract the icon from</param>
    ''' <param name="nIconIndex">Specifies the zero-based index of the icon to extract. If this value is –1 and phiconLarge and phiconSmall are both NULL, the function returns the total number of icons in the specified file</param>
    ''' <param name="phiconLarge">Handle to the large version of the icon requested</param>
    ''' <param name="phiconSmall">handle to the small version of the icon requested</param>
    ''' <param name="nIcons">Number of icons to extract</param>
    <System.Runtime.InteropServices.DllImportAttribute("shell32.dll", EntryPoint:="ExtractIconExW", CallingConvention:=System.Runtime.InteropServices.CallingConvention.StdCall)>
    Public Shared Function ExtractIconExW(<System.Runtime.InteropServices.InAttribute(), System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lpszFile As String, ByVal nIconIndex As Integer, ByRef phiconLarge As System.IntPtr, ByRef phiconSmall As System.IntPtr, ByVal nIcons As UInteger) As UInteger
    End Function

    ''' <summary>
    ''' Destroys an icon and frees any memory the icon occupied
    ''' </summary>
    ''' <param name="hIcon">The handle to the icon to be destroyed</param>
    <System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint:="DestroyIcon")>
    Public Shared Function DestroyIcon(<System.Runtime.InteropServices.InAttribute()> ByVal hIcon As System.IntPtr) As <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean
    End Function

End Class

Console - Get Password with mask character

'https://www.vbforums.com/showthread.php?553416-VB-Net-2005-Mask-Password-in-Console-Application

    Private Function GetPassword(Optional ByVal passwordMask As Char = "*"c) As String
            Dim pwd As String = String.Empty
            Dim sb As New System.Text.StringBuilder()
            Dim cki As ConsoleKeyInfo = Nothing
     
            'Get the password
            Console.Write("Enter password: ")
            While (True)
                While Console.KeyAvailable() = False
                    System.Threading.Thread.Sleep(50)
                End While
                cki = Console.ReadKey(True)
                If cki.Key = ConsoleKey.Enter Then
                    Console.WriteLine()
                    Exit While
                ElseIf cki.Key = ConsoleKey.Backspace Then
                    If sb.Length > 0 Then
                        sb.Length -= 1
                        Console.Write(ChrW(8) & ChrW(32) & ChrW(8))
                    End If
                    Continue While
                ElseIf Asc(cki.KeyChar) < 32 OrElse Asc(cki.KeyChar) > 126 Then
                    Continue While
                End If
                sb.Append(cki.KeyChar)
                Console.Write(passwordMask)
            End While
            pwd = sb.ToString()
            Return pwd
        End Function