forked from dotnet/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchWindow.vb
1206 lines (1091 loc) · 56.7 KB
/
SearchWindow.vb
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'****************************************************************************************
' * File: FindText.cs
' *
' * Description:
' * This sample demonstrates the UI Automation TextPattern and TextPatternRange classes.
' *
' * The sample consists of a Windows Presentation Foundation (WPF) client and the choice
' * of a WPF FlowDocumentReader target or a Win32 WordPad target. The client uses the
' * TextPattern control pattern and the TextPatternRange class to interact with the text
' * controls in either target.
' *
' * The functionality demonstrated by the sample includes the ability to search for and
' * select text, expand a selection to a specific TextUnit, navigate by TextUnit, access
' * embedded objects within a selection, and access the enclosing element of a selection.
' *
' * Note: Three WPF documents, a RichText document, and a plain text document are provided
' * in the Content folder of the TextProvider project.
' *
' *
' * This file is part of the Microsoft .NET Framework SDK Code Samples.
' *
' * Copyright (C) Microsoft Corporation. All rights reserved.
' *
' * This source code is intended only as a supplement to Microsoft
' * Development Tools and/or on-line documentation. See these other
' * materials for detailed information regarding Microsoft code samples.
' *
' * THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
' * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
' * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
' * PARTICULAR PURPOSE.
' *
' *****************************************************************************************
Imports System.Windows
Imports System.Windows.Automation
Imports System.Windows.Controls
Imports System.Diagnostics
Imports System.IO
Imports System.Windows.Automation.Text
Imports System.Text
Imports System.Threading
Imports System.Windows.Threading
Imports System.Windows.Media
Namespace SDKSample
'--------------------------------------------------------------------
' <summary>
' Interaction logic for client and target
' </summary>
'--------------------------------------------------------------------
Public Class SearchWindow
#Region "Member Variables"
' Client application window.
Private clientWindow As Window
' Container for all client controls.
Private clientDockPanel As DockPanel
' Target application window.
Private targetWindow As AutomationElement
' Target text control.
Private targetDocument As AutomationElement
' Text pattern obtained from the target text control.
Private targetTextPattern As TextPattern
' Text range for entire target text control.
Private documentRange As TextPatternRange
' Text range for current selection in target text control.
Private searchRange As TextPatternRange
' Target applications based on underlying framework.
Private startWPFTargetButton As Button
Private startW32TargetButton As Button
Private WPFTarget As String
Private W32Target As String
' Find the target text control.
Private findEditButton As Button
' Display target status.
Private targetResult As Label
' Layout grid for client controls.
Private infoGrid As Grid
' String to search for in the target text control.
Private searchString As TextBox
' Depending on the location of the selection in the target text
' control, the client can search forward or backward for the
' search string.
Private searchBackwardButton As Button
Private searchForwardButton As Button
' Direction of search.
Private searchBackward As Boolean
' Expand the target text selection by the specified text unit.
Private expandHighlight As ComboBox
' Move the target text selection by the specified text unit.
Private navigateTarget As ComboBox
Private navigationUnit As TextUnit
' Display the target text selection and attributes.
Private targetSelectionLabel As Label
Private targetSelectionAttributeLabel As Label
Private targetSelection As TextBox
Private targetSelectionAttributes As TextBox
' Display target text selection details such as child and enclosing unit.
Private targetSelectionDetails As TextBox
' Delegates for updating the client UI based on target application events.
Private Delegate Sub TextChangeDelegate(ByVal message As String)
Private Delegate Sub SelectionChangeDelegate()
Private Delegate Sub ProviderCloseDelegate()
' Target applications.
Private Enum targetApplication
FlowDocument
WordPad
End Enum 'targetApplication ' Search and navigation directions.
Private Enum traversalDirection
Backward
Forward
End Enum 'traversalDirection
#End Region
#Region "Client Setup"
'--------------------------------------------------------------------
' <summary>
' The class constructor.
' </summary>
' <remarks>
' Initialize the WPF client application.
' </remarks>
'--------------------------------------------------------------------
Public Sub SearchWindow()
' Specify the target applications.
WPFTarget = _
System.Windows.Forms.Application.StartupPath + "\TextProvider.exe"
W32Target = "WordPad.exe"
' Initialize search direction.
' Search direction buttons are enabled or disabled based on this value.
searchBackward = False
' Layout the client controls.
Try
' Specs for Window.
Dim clientHeight As Double = 600
Dim clientWidth As Double = 550
' Specs for TextBox.
Dim maxSearchLines As Integer = 1
Dim maxSearchLength As Integer = 25
' Specs for Buttons.
Dim buttonWidth As Double = 140
' Instantiate the client window and set location and size.
clientWindow = New Window()
clientWindow.Height = clientHeight
clientWindow.Width = clientWidth
clientWindow.Left = SystemParameters.WorkArea.Location.X + 50
clientWindow.Top = SystemParameters.WorkArea.Location.Y + 50
clientWindow.Title = "Find Text"
clientWindow.WindowStyle = WindowStyle.ToolWindow
' Create a dock panel to hold all controls.
clientDockPanel = New DockPanel()
clientDockPanel.Margin = New Thickness(10)
clientDockPanel.LastChildFill = True
' Add the start target buttons.
startWPFTargetButton = New Button()
startWPFTargetButton.Width = buttonWidth
startWPFTargetButton.Content = "Start _FlowDocument (WPF)"
startWPFTargetButton.Tag = targetApplication.FlowDocument
AddHandler startWPFTargetButton.Click, AddressOf StartTargetApplication_Click
startW32TargetButton = New Button()
startW32TargetButton.Width = buttonWidth
startW32TargetButton.Content = "Start _WordPad (Win32)"
startW32TargetButton.Tag = targetApplication.WordPad
AddHandler startW32TargetButton.Click, AddressOf StartTargetApplication_Click
DockPanel.SetDock(startWPFTargetButton, Dock.Top)
DockPanel.SetDock(startW32TargetButton, Dock.Top)
clientDockPanel.Children.Add(startWPFTargetButton)
clientDockPanel.Children.Add(startW32TargetButton)
' Add the find text control button.
findEditButton = New Button()
findEditButton.Width = buttonWidth
findEditButton.Content = "_Find text provider"
AddHandler findEditButton.Click, AddressOf FindTextProvider_Click
findEditButton.Visibility = Visibility.Collapsed
DockPanel.SetDock(findEditButton, Dock.Top)
clientDockPanel.Children.Add(findEditButton)
' Add the target status label.
targetResult = New Label()
targetResult.Content = ""
targetResult.BorderThickness = New Thickness(1)
targetResult.BorderBrush = Brushes.Black
targetResult.HorizontalAlignment = HorizontalAlignment.Center
targetResult.Margin = New Thickness(0, 10, 0, 20)
targetResult.Visibility = Visibility.Hidden
DockPanel.SetDock(targetResult, Dock.Top)
clientDockPanel.Children.Add(targetResult)
' Add the client control layout grid.
infoGrid = New Grid()
infoGrid.HorizontalAlignment = HorizontalAlignment.Center
infoGrid.VerticalAlignment = VerticalAlignment.Top
infoGrid.ShowGridLines = False
infoGrid.Visibility = Visibility.Collapsed
infoGrid.MinWidth = 400
' Define the columns.
Dim colDef1 As New ColumnDefinition()
Dim colDef2 As New ColumnDefinition()
infoGrid.ColumnDefinitions.Add(colDef1)
infoGrid.ColumnDefinitions.Add(colDef2)
' Define the rows.
Dim rowDef1 As RowDefinition = New RowDefinition()
rowDef1.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef2 As RowDefinition = New RowDefinition()
rowDef2.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef3 As RowDefinition = New RowDefinition()
rowDef3.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef4 As RowDefinition = New RowDefinition()
rowDef4.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef5 As RowDefinition = New RowDefinition()
rowDef5.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef6 As RowDefinition = New RowDefinition()
rowDef6.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef7 As RowDefinition = New RowDefinition()
rowDef7.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef8 As RowDefinition = New RowDefinition()
rowDef8.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef9 As RowDefinition = New RowDefinition()
rowDef9.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef10 As RowDefinition = New RowDefinition()
rowDef10.Height = New GridLength(1, GridUnitType.Auto)
Dim rowDef11 As RowDefinition = New RowDefinition()
rowDef11.Height = New GridLength(1, GridUnitType.Auto)
infoGrid.RowDefinitions.Add(rowDef1)
infoGrid.RowDefinitions.Add(rowDef2)
infoGrid.RowDefinitions.Add(rowDef3)
infoGrid.RowDefinitions.Add(rowDef4)
infoGrid.RowDefinitions.Add(rowDef5)
infoGrid.RowDefinitions.Add(rowDef6)
infoGrid.RowDefinitions.Add(rowDef7)
infoGrid.RowDefinitions.Add(rowDef8)
infoGrid.RowDefinitions.Add(rowDef9)
infoGrid.RowDefinitions.Add(rowDef10)
infoGrid.RowDefinitions.Add(rowDef11)
' Define the content of the cells.
' Row 1 - search string details.
searchString = New TextBox()
searchString.Name = "SearchString"
searchString.MaxLines = maxSearchLines
searchString.MaxLength = maxSearchLength
searchString.Width = 200
AddHandler searchString.TextChanged, AddressOf SearchString_Change
searchString.IsEnabled = False
Grid.SetRow(searchString, 0)
Grid.SetColumn(searchString, 1)
Dim searchLabel As New Label()
searchLabel.Target = searchString
searchLabel.Content = "_Search for: "
searchLabel.VerticalAlignment = VerticalAlignment.Center
Grid.SetRow(searchLabel, 0)
Grid.SetColumn(searchLabel, 0)
infoGrid.Children.Add(searchLabel)
infoGrid.Children.Add(searchString)
' Row 2 - search direction buttons.
searchBackwardButton = New Button()
searchBackwardButton.Width = buttonWidth
searchBackwardButton.Content = "Search _Backward"
searchBackwardButton.Tag = traversalDirection.Backward
AddHandler searchBackwardButton.Click, AddressOf SearchDirection_Click
searchBackwardButton.Margin = New Thickness(0, 0, 0, 10)
searchBackwardButton.IsEnabled = False
Grid.SetRow(searchBackwardButton, 1)
Grid.SetColumn(searchBackwardButton, 0)
searchForwardButton = New Button()
searchForwardButton.Width = buttonWidth
searchForwardButton.Content = "Search _Forward"
searchForwardButton.Tag = traversalDirection.Forward
AddHandler searchForwardButton.Click, AddressOf SearchDirection_Click
searchForwardButton.Margin = New Thickness(0, 0, 0, 10)
searchForwardButton.IsEnabled = False
Grid.SetRow(searchForwardButton, 1)
Grid.SetColumn(searchForwardButton, 1)
infoGrid.Children.Add(searchBackwardButton)
infoGrid.Children.Add(searchForwardButton)
' Row 3 - Target selection.
targetSelectionLabel = New Label()
targetSelectionLabel.Target = targetSelection
targetSelectionLabel.Content = "Currently selected:"
Grid.SetRow(targetSelectionLabel, 2)
Grid.SetColumn(targetSelectionLabel, 0)
Grid.SetColumnSpan(targetSelectionLabel, 2)
infoGrid.Children.Add(targetSelectionLabel)
' Row 4.
targetSelection = New TextBox()
targetSelection.TextWrapping = TextWrapping.Wrap
targetSelection.MaxWidth = 400
targetSelection.Height = 100
targetSelection.VerticalScrollBarVisibility = _
ScrollBarVisibility.Auto
targetSelection.IsReadOnly = True
targetSelection.Margin = New Thickness(0, 0, 0, 0)
Grid.SetRow(targetSelection, 3)
Grid.SetColumn(targetSelection, 0)
Grid.SetColumnSpan(targetSelection, 2)
infoGrid.Children.Add(targetSelection)
' Row 5 - Target selection attributes.
targetSelectionAttributeLabel = New Label()
targetSelectionAttributeLabel.Target = targetSelection
targetSelectionAttributeLabel.Content = "Attribute values: "
Grid.SetRow(targetSelectionAttributeLabel, 4)
Grid.SetColumn(targetSelectionAttributeLabel, 0)
Grid.SetColumnSpan(targetSelectionAttributeLabel, 2)
infoGrid.Children.Add(targetSelectionAttributeLabel)
' Row 6.
targetSelectionAttributes = New TextBox()
targetSelectionAttributes.TextWrapping = TextWrapping.Wrap
targetSelectionAttributes.MaxWidth = 400
targetSelectionAttributes.Height = 100
targetSelectionAttributes.VerticalScrollBarVisibility = _
ScrollBarVisibility.Auto
targetSelectionAttributes.IsReadOnly = True
targetSelectionAttributes.Margin = New Thickness(0, 0, 0, 10)
Grid.SetRow(targetSelectionAttributes, 5)
Grid.SetColumn(targetSelectionAttributes, 0)
Grid.SetColumnSpan(targetSelectionAttributes, 2)
infoGrid.Children.Add(targetSelectionAttributes)
' Row 7 - Navigate target details.
navigateTarget = New ComboBox()
navigateTarget.Width = buttonWidth
navigateTarget.Items.Add(TextUnit.Character)
navigateTarget.Items.Add(TextUnit.Format)
navigateTarget.Items.Add(TextUnit.Word)
navigateTarget.Items.Add(TextUnit.Line)
navigateTarget.Items.Add(TextUnit.Paragraph)
navigateTarget.Items.Add(TextUnit.Page)
navigateTarget.SelectedIndex = 0
AddHandler navigateTarget.SelectionChanged, _
New SelectionChangedEventHandler(AddressOf NavigationUnit_Change)
Grid.SetRow(navigateTarget, 6)
Grid.SetColumn(navigateTarget, 1)
Dim navigateLabel As Label = New Label()
navigateLabel.Target = navigateTarget
navigateLabel.Content = "_Navigate target by text unit of: "
navigateLabel.VerticalAlignment = VerticalAlignment.Center
Grid.SetRow(navigateLabel, 6)
Grid.SetColumn(navigateLabel, 0)
infoGrid.Children.Add(navigateLabel)
infoGrid.Children.Add(navigateTarget)
' Row 8 - Navigate target direction buttons.
Dim navigateBackwardButton As Button = New Button()
navigateBackwardButton.Width = buttonWidth
navigateBackwardButton.Content = "_Backward"
navigateBackwardButton.Tag = traversalDirection.Backward
AddHandler navigateBackwardButton.Click, _
New RoutedEventHandler(AddressOf Navigate_Click)
navigateBackwardButton.Margin = New Thickness(0, 0, 0, 10)
Grid.SetRow(navigateBackwardButton, 7)
Grid.SetColumn(navigateBackwardButton, 0)
Dim navigateForwardButton As Button = New Button()
navigateForwardButton.Width = buttonWidth
navigateForwardButton.Content = "_Forward"
navigateForwardButton.Tag = traversalDirection.Forward
AddHandler navigateForwardButton.Click, _
New RoutedEventHandler(AddressOf Navigate_Click)
navigateForwardButton.Margin = New Thickness(0, 0, 0, 10)
Grid.SetRow(navigateForwardButton, 7)
Grid.SetColumn(navigateForwardButton, 1)
infoGrid.Children.Add(navigateBackwardButton)
infoGrid.Children.Add(navigateForwardButton)
' Row 9 - Expand the target selection controls.
expandHighlight = New ComboBox()
expandHighlight.Width = buttonWidth
expandHighlight.Items.Add("")
expandHighlight.Items.Add("None")
expandHighlight.Items.Add(TextUnit.Character)
expandHighlight.Items.Add(TextUnit.Format)
expandHighlight.Items.Add(TextUnit.Word)
expandHighlight.Items.Add(TextUnit.Line)
expandHighlight.Items.Add(TextUnit.Paragraph)
expandHighlight.Items.Add(TextUnit.Page)
expandHighlight.Items.Add(TextUnit.Document)
expandHighlight.SelectedIndex = 0
AddHandler expandHighlight.SelectionChanged, _
New SelectionChangedEventHandler(AddressOf ExpandToTextUnit_Change)
expandHighlight.Margin = New Thickness(0, 0, 0, 10)
Grid.SetRow(expandHighlight, 8)
Grid.SetColumn(expandHighlight, 1)
Dim expandLabel As Label = New Label()
expandLabel.Target = expandHighlight
expandLabel.Content = "_Expand selection to text unit of: "
expandLabel.VerticalAlignment = VerticalAlignment.Center
expandLabel.Margin = New Thickness(0, 0, 0, 10)
Grid.SetRow(expandLabel, 8)
Grid.SetColumn(expandLabel, 0)
infoGrid.Children.Add(expandLabel)
infoGrid.Children.Add(expandHighlight)
' Row 10 - target selection details such as child elements
' and enclosing unit.
targetSelectionDetails = New TextBox()
targetSelectionDetails.Height = 100
targetSelectionDetails.VerticalScrollBarVisibility = _
ScrollBarVisibility.Auto
targetSelectionDetails.IsReadOnly = True
Grid.SetRow(targetSelectionDetails, 9)
Grid.SetColumn(targetSelectionDetails, 0)
Grid.SetColumnSpan(targetSelectionDetails, 2)
infoGrid.Children.Add(targetSelectionDetails)
' Row 11 - get the child elements and the enclosing unit
' of the target selection.
Dim getChildren As Button = New Button()
getChildren.Width = buttonWidth
getChildren.Content = "Get children of selection"
AddHandler getChildren.Click, _
New RoutedEventHandler(AddressOf GetChildren_Click)
Grid.SetRow(getChildren, 10)
Grid.SetColumn(getChildren, 0)
Dim getEnclosingElement As Button = New Button()
getEnclosingElement.Width = buttonWidth
getEnclosingElement.Content = "Get enclosing element"
AddHandler getEnclosingElement.Click, _
New RoutedEventHandler(AddressOf GetEnclosingElement_Click)
Grid.SetRow(getEnclosingElement, 10)
Grid.SetColumn(getEnclosingElement, 1)
infoGrid.Children.Add(getChildren)
infoGrid.Children.Add(getEnclosingElement)
' Add the grid to the dock panel.
DockPanel.SetDock(infoGrid, Dock.Top)
clientDockPanel.Children.Add(infoGrid)
' Add the dock panel to the window.
clientWindow.Content = clientDockPanel
clientWindow.Show()
' Do we successfully create the client app?
Catch
' TODO: error handling.
Return
End Try
End Sub
'--------------------------------------------------------------------
' <summary>
' Handles the Start Application button click.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
' <remarks>
' Starts the application that we are going to use for as our
' root element for this sample.
' </remarks>
'--------------------------------------------------------------------
Private Sub StartTargetApplication_Click( _
ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim targetOption As Button = CType(sender, Button)
' Start the target selected by the user.
If CType(targetOption.Tag, targetApplication) = _
targetApplication.WordPad Then
targetWindow = StartApp(W32Target)
Else
targetWindow = StartApp(WPFTarget)
End If
' Target is not available.
Debug.Assert(Not (targetWindow Is Nothing))
Dim targetCloseListener As AutomationEventHandler = _
New AutomationEventHandler(AddressOf OnTargetClose)
' Set a listener for the window closed event on the target.
Automation.AddAutomationEventHandler( _
WindowPattern.WindowClosedEvent, _
targetWindow, TreeScope.Element, targetCloseListener)
' Set size and position of target.
' Since the target is started and manipulated from the client
' and both windows show UI changes this section of code just
' ensures neither window obscures the other.
Dim targetTransformPattern As TransformPattern = _
DirectCast(targetWindow.GetCurrentPattern( _
TransformPattern.Pattern), TransformPattern)
targetTransformPattern.Resize(clientWindow.Width, clientWindow.Height)
targetTransformPattern.Move( _
clientWindow.Left + clientWindow.Width + 25, clientWindow.Top)
' Set visibility of client controls.
startWPFTargetButton.Visibility = Visibility.Collapsed
startW32TargetButton.Visibility = Visibility.Collapsed
findEditButton.Visibility = Visibility.Visible
targetResult.Visibility = Visibility.Visible
End Sub
'<SnippetStartApp>
'--------------------------------------------------------------------
' <summary>
' Starts the target application.
' </summary>
' <param name="app">
' The application to start.
' </param>
' <returns>The automation element for the app main window.</returns>
' <remarks>
' Three WPF documents, a rich text document, and a plain text document
' are provided in the Content folder of the TextProvider project.
' </remarks>
'--------------------------------------------------------------------
Private Function StartApp(ByVal app As String) As AutomationElement
' Start application.
Dim p As Process = Process.Start(app)
' Give the target application some time to start.
' For Win32 applications, WaitForInputIdle can be used instead.
' Another alternative is to listen for WindowOpened events.
' Otherwise, an ArgumentException results when you try to
' retrieve an automation element from the window handle.
Thread.Sleep(2000)
targetResult.Content = WPFTarget + " started. " + vbLf + vbLf + _
"Please load a document into the target application and click " + _
"the 'Find edit control' button above. " + vbLf + vbLf + _
"NOTE: Documents can be found in the 'Content' folder of the FindText project."
targetResult.Background = Brushes.LightGreen
' Return the automation element for the app main window.
Return AutomationElement.FromHandle(p.MainWindowHandle)
End Function 'StartApp
'</SnippetStartApp>
#End Region
#Region "Target Text Info"
'<SnippetFindTextProvider>
'--------------------------------------------------------------------
' <summary>
' Finds the text control in our target.
' </summary>
' <param name="src">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
' <remarks>
' Initializes the TextPattern object and event handlers.
' </remarks>
'--------------------------------------------------------------------
Private Sub FindTextProvider_Click( _
ByVal src As Object, ByVal e As RoutedEventArgs)
'<SnippetTextPatternPattern>
' Set up the conditions for finding the text control.
Dim documentControl As New PropertyCondition( _
AutomationElement.ControlTypeProperty, ControlType.Document)
Dim textPatternAvailable As New PropertyCondition( _
AutomationElement.IsTextPatternAvailableProperty, True)
Dim findControl As New AndCondition(documentControl, textPatternAvailable)
' Get the Automation Element for the first text control found.
' For the purposes of this sample it is sufficient to find the
' first text control. In other cases there may be multiple text
' controls to sort through.
targetDocument = targetWindow.FindFirst(TreeScope.Descendants, findControl)
' Didn't find a text control.
If targetDocument Is Nothing Then
targetResult.Content = _
WPFTarget + " does not contain a Document control type."
targetResult.Background = Brushes.Salmon
startWPFTargetButton.IsEnabled = False
Return
End If
' Get required control patterns
targetTextPattern = DirectCast( _
targetDocument.GetCurrentPattern(TextPattern.Pattern), TextPattern)
' Didn't find a text control that supports TextPattern.
If targetTextPattern Is Nothing Then
targetResult.Content = WPFTarget + _
" does not contain an element that supports TextPattern."
targetResult.Background = Brushes.Salmon
startWPFTargetButton.IsEnabled = False
Return
End If
'</SnippetTextPatternPattern>
' Text control is available so display the client controls.
infoGrid.Visibility = Visibility.Visible
targetResult.Content = "Text provider found."
targetResult.Background = Brushes.LightGreen
'<SnippetDocumentRange>
' Initialize the document range for the text of the document.
documentRange = targetTextPattern.DocumentRange
'</SnippetDocumentRange>
' Initialize the client's search buttons.
If targetTextPattern.DocumentRange.GetText(1).Length > 0 Then
searchForwardButton.IsEnabled = True
End If
' Initialize the client's search TextBox.
searchString.IsEnabled = True
' Check if the text control supports text selection
If targetTextPattern.SupportedTextSelection = SupportedTextSelection.None Then
targetResult.Content = "Unable to select text."
targetResult.Background = Brushes.Salmon
Return
End If
' Edit control found so remove the find button from the client.
findEditButton.Visibility = Visibility.Collapsed
' Initialize the client with the current target selection, if any.
NotifySelectionChanged()
' Search starts at beginning of doc and goes forward
searchBackward = False
'<SnippetTextChanged>
' Initialize a text changed listener.
' An instance of TextPatternRange will become invalid if
' one of the following occurs:
' 1) The text in the provider changes via some user activity.
' 2) ValuePattern.SetValue is used to programmatically change
' the value of the text in the provider.
' The only way the client application can detect if the text
' has changed (to ensure that the ranges are still valid),
' is by setting a listener for the TextChanged event of
' the TextPattern. If this event is raised, the client needs
' to update the targetDocumentRange member data to ensure the
' user is working with the updated text.
' Clients must always anticipate the possibility that the text
' can change underneath them.
Dim onTextChanged As AutomationEventHandler = _
New AutomationEventHandler(AddressOf TextChanged)
Automation.AddAutomationEventHandler( _
TextPattern.TextChangedEvent, targetDocument, TreeScope.Element, onTextChanged)
'</SnippetTextChanged>
'<SnippetSelectionChanged>
' Initialize a selection changed listener.
' The target selection is reflected in the client.
Dim onSelectionChanged As AutomationEventHandler = _
New AutomationEventHandler(AddressOf OnTextSelectionChange)
Automation.AddAutomationEventHandler( _
TextPattern.TextSelectionChangedEvent, targetDocument, _
TreeScope.Element, onSelectionChanged)
'</SnippetSelectionChanged>
End Sub
'</SnippetFindTextProvider>
'--------------------------------------------------------------------
' <summary>
' Gets the enclosing element of the target selection.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
'--------------------------------------------------------------------
Private Sub GetEnclosingElement_Click( _
ByVal sender As Object, ByVal e As RoutedEventArgs)
' Obtain the enclosing element.
Dim enclosingElement As AutomationElement
Try
enclosingElement = searchRange.GetEnclosingElement()
Catch
' TODO: error handling.
Return
End Try
' Assemble the information about the enclosing element.
Dim enclosingElementInformation As New StringBuilder()
enclosingElementInformation.Append("Enclosing element:" + vbTab) _
.AppendLine(enclosingElement.Current.ControlType.ProgrammaticName)
' The WPF target doesn't show selected text as highlighted unless
' the window has focus.
targetWindow.SetFocus()
' Display the enclosing element information in the client.
targetSelectionDetails.Text = enclosingElementInformation.ToString()
' Is the enclosing element the entire document?
' If so, select the document.
If enclosingElement = targetDocument Then
documentRange = targetTextPattern.DocumentRange
documentRange.Select()
Return
End If
' Otherwise, select the range from the child element.
Dim childRange As TextPatternRange = _
documentRange.TextPattern.RangeFromChild(enclosingElement)
childRange.Select()
End Sub
' <SnippetGetChildren>
'--------------------------------------------------------------------
' <summary>
' Gets the children of the target selection.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
'--------------------------------------------------------------------
Private Sub GetChildren_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Obtain an array of child elements.
Dim textProviderChildren() As AutomationElement
Try
textProviderChildren = searchRange.GetChildren()
Catch
' TODO: error handling.
Return
End Try
' Assemble the information about the enclosing element.
Dim childInformation As New StringBuilder()
childInformation.Append(textProviderChildren.Length).AppendLine(" child element(s).")
' Iterate through the collection of child elements and obtain
' information of interest about each.
Dim i As Integer
For i = 0 To textProviderChildren.Length - 1
childInformation.Append("Child").Append(i).AppendLine(":")
' Obtain the name of the child control.
childInformation.Append(vbTab + "Name:" + vbTab) _
.AppendLine(textProviderChildren(i).Current.Name)
' Obtain the control type.
childInformation.Append(vbTab + "Control Type:" + vbTab) _
.AppendLine(textProviderChildren(i).Current.ControlType.ProgrammaticName)
' Obtain the supported control patterns.
' NOTE: For the purposes of this sample we use GetSupportedPatterns().
' However, the use of GetSupportedPatterns() is strongly discouraged
' as it calls GetCurrentPattern() internally on every known pattern.
' It is therefore much more efficient to use GetCurrentPattern() for
' the specific patterns you are interested in.
Dim childPatterns As AutomationPattern() = _
textProviderChildren(i).GetSupportedPatterns()
childInformation.AppendLine(vbTab + "Supported Control Patterns:")
If childPatterns.Length <= 0 Then
childInformation.AppendLine(vbTab + vbTab + vbTab + "None")
Else
Dim pattern As AutomationPattern
For Each pattern In childPatterns
childInformation.Append(vbTab + vbTab + vbTab) _
.AppendLine(pattern.ProgrammaticName)
Next pattern
End If
' Obtain the child elements, if any, of the child control.
Dim childRange As TextPatternRange = _
documentRange.TextPattern.RangeFromChild(textProviderChildren(i))
Dim childRangeChildren As AutomationElement() = _
childRange.GetChildren()
childInformation.Append(vbTab + "Children: " + vbTab) _
.Append(childRangeChildren.Length).AppendLine()
Next i
' Display the information about the child controls.
targetSelectionDetails.Text = childInformation.ToString()
End Sub
'</SnippetGetChildren>
#End Region
#Region "Search Target"
'<SnippetSearchTarget>
'--------------------------------------------------------------------
' <summary>
' Handles changes to the search text in the client.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
' <remarks>
' Reset all controls if user changes search text
' </remarks>
'--------------------------------------------------------------------
Private Sub SearchString_Change( _
ByVal sender As Object, ByVal e As TextChangedEventArgs)
Dim startPoints As Integer = _
documentRange.CompareEndpoints( _
TextPatternRangeEndpoint.Start, searchRange, _
TextPatternRangeEndpoint.Start)
Dim endPoints As Integer = _
documentRange.CompareEndpoints(TextPatternRangeEndpoint.End, _
searchRange, TextPatternRangeEndpoint.End)
' If the starting endpoints of the document range and the search
' range are equivalent then we can search forward only since the
' search range is at the start of the document.
If startPoints = 0 Then
searchForwardButton.IsEnabled = True
searchBackwardButton.IsEnabled = False
' If the ending endpoints of the document range and the search
' range are identical then we can search backward only since the
' search range is at the end of the document.
ElseIf endPoints = 0 Then
searchForwardButton.IsEnabled = False
searchBackwardButton.IsEnabled = True
' Otherwise we can search both directions.
Else
searchForwardButton.IsEnabled = True
searchBackwardButton.IsEnabled = True
End If
End Sub
'--------------------------------------------------------------------
' <summary>
' Handles the Search button click.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
' <remarks>Find the text specified in the text box.</remarks>
'--------------------------------------------------------------------
Private Sub SearchDirection_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim searchDirection As Button = CType(sender, Button)
' Are we searching backward through the text control?
searchBackward = _
(CType(searchDirection.Tag, traversalDirection) = traversalDirection.Backward)
' Check if search text entered
If searchString.Text.Trim() = "" Then
targetResult.Content = "No search criteria."
targetResult.Background = Brushes.Salmon
Return
End If
'<SnippetSupportedTextSelection>
' Does target range support text selection?
If targetTextPattern.SupportedTextSelection = SupportedTextSelection.None Then
targetResult.Content = "Unable to select text."
targetResult.Background = Brushes.Salmon
Return
End If
' Does target range support multiple selections?
If targetTextPattern.SupportedTextSelection = SupportedTextSelection.Multiple Then
targetResult.Content = "Multiple selections present."
targetResult.Background = Brushes.Salmon
Return
End If
'</SnippetSupportedTextSelection>
' Clone the document range since we modify the endpoints
' as we search.
Dim documentRangeClone As TextPatternRange = documentRange.Clone()
' Move the cloned document range endpoints to enable the
' selection of the next matching text range.
Dim selectionRange As TextPatternRange() = targetTextPattern.GetSelection()
If Not (selectionRange(0) Is Nothing) Then
If searchBackward Then
documentRangeClone.MoveEndpointByRange( _
TextPatternRangeEndpoint.End, selectionRange(0), _
TextPatternRangeEndpoint.Start)
Else
documentRangeClone.MoveEndpointByRange( _
TextPatternRangeEndpoint.Start, selectionRange(0), _
TextPatternRangeEndpoint.End)
End If
End If
' Find the text specified in the Search textbox.
' Clone the search range since we need to modify it.
Dim searchRangeClone As TextPatternRange = searchRange.Clone()
' backward = false? -- search forward, otherwise backward.
' ignoreCase = false? -- search is case sensitive.
searchRange = documentRangeClone.FindText(searchString.Text, searchBackward, False)
' Search unsuccessful.
If searchRange Is Nothing Then
' Search string not found at all.
If documentRangeClone.CompareEndpoints( _
TextPatternRangeEndpoint.Start, searchRangeClone, _
TextPatternRangeEndpoint.Start) = 0 Then
targetResult.Content = "Text not found."
targetResult.Background = Brushes.Wheat
searchBackwardButton.IsEnabled = False
searchForwardButton.IsEnabled = False
Else
' End of document (either the start or end of the document
' range depending on search direction) was reached before
' finding another occurrence of the search string.
targetResult.Content = "End of document reached."
targetResult.Background = Brushes.Wheat
If Not searchBackward Then
searchRangeClone.MoveEndpointByRange( _
TextPatternRangeEndpoint.Start, documentRange, _
TextPatternRangeEndpoint.End)
searchBackwardButton.IsEnabled = True
searchForwardButton.IsEnabled = False
Else
searchRangeClone.MoveEndpointByRange( _
TextPatternRangeEndpoint.End, documentRange, _
TextPatternRangeEndpoint.Start)
searchBackwardButton.IsEnabled = False
searchForwardButton.IsEnabled = True
End If
End If
searchRange = searchRangeClone
Else
' The search string was found.
targetResult.Content = "Text found."
targetResult.Background = Brushes.LightGreen
End If
searchRange.Select()
' Scroll the selection into view and align with top of viewport
searchRange.ScrollIntoView(True)
' The WPF target doesn't show selected text as highlighted unless
' the window has focus.
targetWindow.SetFocus()
End Sub
'</SnippetSearchTarget>
#End Region
#Region "Target Navigation"
' <SnippetNavigate>
'--------------------------------------------------------------------
' <summary>
' Handles the navigation item selected event.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
'--------------------------------------------------------------------
Private Sub NavigationUnit_Change( _
ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
Dim cb As ComboBox = CType(sender, ComboBox)
navigationUnit = CType(cb.SelectedValue, TextUnit)
End Sub
'--------------------------------------------------------------------
' <summary>
' Handles the Navigate button click event.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
'--------------------------------------------------------------------
Private Sub Navigate_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim moveSelection As Button = CType(sender, Button)
Dim navDirection As Integer
' Which direction is the user searching through the text control?
If (CType(moveSelection.Tag, traversalDirection) = traversalDirection.Forward) Then
navDirection = 1
Else
navDirection = -1
End If
' Obtain the ranges to move.
Dim selectionRanges As TextPatternRange() = targetTextPattern.GetSelection()
' Iterate through the ranges for a text control that supports
' multiple selections and move the selections the specified text
' unit and direction.
Dim textRange As TextPatternRange
For Each textRange In selectionRanges
textRange.Move(navigationUnit, navDirection)
textRange.Select()
Next textRange
' The WPF target doesn't show selected text as highlighted unless
' the window has focus.
targetDocument.SetFocus()
End Sub
' </SnippetNavigate>
#End Region
#Region "Expand Selection"
'--------------------------------------------------------------------
' <summary>
' Handles the expand to enclosing unit item selected event.
' </summary>
' <param name="sender">The object that raised the event.</param>
' <param name="e">Event arguments.</param>
'--------------------------------------------------------------------
Private Sub ExpandToTextUnit_Change( _
ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
Dim cb As ComboBox = CType(sender, ComboBox)
' Expand the target selection to the selected text unit.
Dim selectionRanges As TextPatternRange() = _
targetTextPattern.GetSelection()
Dim textRange As TextPatternRange
For Each textRange In selectionRanges
Select Case cb.SelectedValue.ToString()