using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SpellCheckerSample
{
    /// <summary>
    /// Extends <see cref="TextBox"/> with a <see cref="HideSelection"/> property to allow showing 
    /// the selection even when the control doesn't have the focus.
    /// </summary>
    public class TextBoxHideSelection : TextBox
    {
        // ** fields
        bool _hideSelection = false;

        // ** ctor
        public TextBoxHideSelection()
        {
            // too bad there isn't an OnSelectionChanged method we can override...
            this.SelectionChanged += new RoutedEventHandler(TextBoxVisibleSelection_SelectionChanged);
        }

        // ** object model
        public bool HideSelection
        {
            get { return _hideSelection; }
            set
            {
                _hideSelection = value;
                TextBoxVisibleSelection_SelectionChanged(this, new RoutedEventArgs());
            }
        }

        // optionally show selection even without the focus
        void TextBoxVisibleSelection_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (!_hideSelection && FocusManager.GetFocusedElement() != this)
            {
                // make control show the selection by raising a fake GotFocus event.
                // this is really cheesy, but it's the only way I found to make the TextBox
                // show the selection even when it doesn't really have the focus.
                // I hope MS will fix that soon...
                base.OnGotFocus(e);
            }
        }
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            if (!_hideSelection)
            {
                base.OnGotFocus(e);
            }
        }
    }
}
