Marvin Dickhaus
Marvin Dickhaus

Reputation: 805

Mimic Disabled Focus Behaviour in WinForms

In accordance to this Post I'm trying to mimic the behavior of

Enabled = False

without actually disable the Control. (In my case a multiline TextBox)

The next I'm trying to accomplish is to mimic the focus behavior by mouse of a disabled control. If I click on a disabled control it won't get the focus and the control that previously had focus won't loose the focus.

What I came up with so far: I can intercept the WM_SETFOCUS message in WndProc so my control won't recieve focus.

Private Const WM_SETFOCUS = &H7

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If Me.ReadOnly AndAlso (m.Msg = WM_SETFOCUS) Then Exit Sub
    MyBase.WndProc(m)
End Sub

The problem with that is, that the previous contol lost the focus, which isn't intended. How do I prevent that even the click by mouse will do anything in the focus behaviour? Is there any way to do this?

Update: 06.08.12

As suggested by Justin I solved the problem by changing it to a label in an autoscroll panel. A minimal code example is as followed:

Imports System.Windows.Forms

Public Class ScrollableDisabledTextBox
    Inherits TextBox

    Private xLabel As Label
    Private xPanel As Panel

    Public Sub New()
        InizializeComponent()
    End Sub

    Private Sub InizializeComponent()
        xPanel = New Panel
        xPanel.AutoScroll = True
        xPanel.BorderStyle = BorderStyle.FixedSingle

        xLabel = New Label
        xLabel.Enabled = False
        xLabel.AutoSize = True
        xPanel.Controls.Add(xLabel)

        Me.Me_SizeChanged()
    End Sub

    Private Sub Me_EnabledChanged() Handles Me.EnabledChanged
        If Me.Enabled Then
            Me.Show()
            xPanel.Hide()
        Else
            xPanel.Show()
            Me.SendToBack()
            Me.Hide()
        End If
    End Sub

    Private Sub Me_TextChanged() Handles Me.TextChanged
        xLabel.Text = Me.Text
    End Sub

    Private Sub Me_SizeChanged() Handles Me.SizeChanged
        xPanel.Size = Me.Size
        xLabel.MaximumSize = New System.Drawing.Size(xPanel.Size.Width, 0)
    End Sub

    Private Sub Me_ParentChanged() Handles Me.ParentChanged
        xPanel.Location = Me.Location
        'If parent changed multiple times, remember to remove panel from old parent!
        If Not Me.Parent.Controls.Contains(xPanel) Then
            Me.Parent.Controls.Add(xPanel)
        End If
    End Sub

End Class

Upvotes: 0

Views: 530

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67135

I do not believe what you want to do is possible. If you do not have focus, then the scrolling will not work.

However, I posit that you should rethink your original problem. Why not use an AutoSize = true, MaximumSize.Width = ParentWidth label (which could be disabled) inside of a panel that will autoscroll. This sounds like what you are really looking for.

Upvotes: 1

Related Questions