summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrakeWPF/Behaviours/DoubleClickFileBehaviours.cs
blob: d7358e117c0acf9ce9b81bf4e9998621eb9d5ec0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DoubleClickFileBehaviours.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   Improve the behaviour of textboxes including file paths. - Select the full filename.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrakeWPF.Behaviours
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Forms.VisualStyles;
    using System.Windows.Interactivity;

    public class DoubleClickFileBehaviours : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            AssociatedObject.MouseDoubleClick += AssociatedObjectMouseDoubleClick;
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseDoubleClick -= AssociatedObjectMouseDoubleClick;
            base.OnDetaching();
        }

        private void AssociatedObjectMouseDoubleClick(object sender, RoutedEventArgs routedEventArgs)
        {
            TextBox tb = sender as TextBox;

            if (tb != null)
            {
                string filePath = tb.Text;
                if (!string.IsNullOrEmpty(filePath))
                {
                    try
                    {
                        string filename = Path.GetFileNameWithoutExtension(filePath);
                        string extension = Path.GetExtension(filePath);

                        long index = tb.CaretIndex;
                        int filenameIndex = filePath.IndexOf(filename, StringComparison.Ordinal);
                        int extensionIndex = filePath.IndexOf(extension, StringComparison.Ordinal);

                        if (index >= filenameIndex && index < extensionIndex)
                        {
                            tb.Select(filenameIndex, filename.Length);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }
                }
            }
        }
    }
}