Andrew Henz
Andrew Henz

Reputation: 35

Change Caret Color in textbox

I use this code to create a caret in a textbox (vb.net):

Private Declare Function CreateCaret Lib "user32" (ByVal hwnd As Long, ByVal hBitmap As Long, ByVal nWidth As Long, ByVal nHeight As Long) As Long
Private Declare Function DestroyCaret Lib "user32" () As Long
Private Declare Function SetCaretBlinkTime Lib "user32" (ByVal wMSeconds As Long) As Long
Private Declare Function SetCaretPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Private Declare Function ShowCaret Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function HideCaret Lib "user32" (ByVal hwnd As Long) As Long
Private Sub txtOutput_GotFocus(sender As Object, e As EventArgs) Handles txtOutput.GotFocus
    CreateCaret(txtOutput.Handle, IntPtr.Zero, 9, 12)
    ShowCaret(txtOutput.Handle)
End Sub

Is it possible to change the color of the caret?

Upvotes: 1

Views: 1310

Answers (1)

Brandon
Brandon

Reputation: 4593

The problem you have is your PInvoke functions aren't declared properly. Look them up and match them with http://pinvoke.net/.

The calls to create the caret will take a bitmap handle. So depending on what your caret looks like, you just need to create a bitmap and pass it to the CreateCaret function to change it's color. Here's some (very) rough code I used to change the caret color of a regular textbox. Just note that I only changed CreateCaret and ShowCaret to the proper signatures from http://www.pinvoke.net. You will have to change the rest.

Public Class Form1
    Private Declare Function CreateCaret Lib "user32" (ByVal hWnd As IntPtr, ByVal hBitmap As IntPtr, ByVal nWidth As Integer, ByVal nHeight As Integer) As Boolean
    Private Declare Function DestroyCaret Lib "user32" () As Long
    Private Declare Function SetCaretBlinkTime Lib "user32" (ByVal wMSeconds As Long) As Long
    Private Declare Function SetCaretPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Private Declare Function ShowCaret Lib "user32" (ByVal hwnd As IntPtr) As Boolean
    Private Declare Function HideCaret Lib "user32" (ByVal hwnd As Long) As Long

    Private caretBitmap as Bitmap
    Private Sub txtOutput_GotFocus(sender As Object, e As EventArgs) Handles txtOutput.GotFocus
        If caretBitmap Is Nothing Then
            caretBitmap = CreateCaretBitmap()
        End If
        CreateCaret(txtOutput.Handle, caretBitmap.GetHbitmap(), 5, 10)
        ShowCaret(txtOutput.Handle)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Function CreateCaretBitmap() As Bitmap
        Dim flag As New Bitmap(5, 5)
        Dim flagGraphics As Graphics = Graphics.FromImage(flag)

        flagGraphics.FillRectangle(Brushes.Chartreuse, 0, 0, 5, 10)
        Return flag

    End Function
End Class

You can create the bitmap however you want obviously.

Hope that helps.

Upvotes: 3

Related Questions