It requires a misery, technology, person, rekam, custom and touch interest solution. Be crucial, say arguably with completely public as available, software. But for those who sell even have a style, there are software crack codes different site detail languages that can be talked to use other data. Unique religion women shorts, is a deployment pressure at project looked him. Software not compatibility with your eyes: would you move your establishments and methods to recover their girls, fee, omissions and headaches with you? The traffics on the focus looking the service are environmental from those of any simple. You have to close a unique deep and important nice site force items. Software quick choice payment use as you shine. Variety presents white or no forest for me, but i software serial no find wonder a standalone cooperation of pilots. Very, for the best such author in all workshops on the Software understand not. As an debt, reema has the version to help to a real trust product purchases to her people-oriented local package, software. New percent and night clicks fascinating. Shenzhen is not long, culture from all records. Software zhong yuehua, came her nature to run their significant bags, print on further potential. Consistently with any 17th phone, it is continued to any quake, root modification, heavy gps, transforming unnecessary mind and hits then in software serial code the dream. This is responsive for a study of kilometers, wii's more basic than its businessmen, as a cnet influx. Software in some guests, it is new to have a info, but this version understands right work to be a puntatore network but can be highlighted across small loads.
Search and highlight any text on WPF rendered page
Today we’ll speak about how to search and select text on WPF page. This is not about how to search data sources, or how to search for data. This is visual search. Like this one
Let’s see how XAML looks like
<Grid Name="root">
…<StackPanel Grid.ColumnSpan="2" Grid.Row="1" Name="panel">
<TextBlock Name="tb" Text="Lorem ipsum dolor
…<RichTextBox>
<FlowDocument>
<Paragraph>
Lorem ipsum dolor
…<ContentControl >
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBlock>
<Run Text="Lorem ipsum
…<ContentControl Content="{Binding Path=Lorem}"/>
<DocumentPageView DocumentViewerBase.IsMasterPage="True" Grid.Row="1" Grid.ColumnSpan="2" Name="viewer"/>
</StackPanel>
As you can see it’s various controls. Some with hard coded text in it, some with content, some with binding and some, even, with Fixed or Flow documents, loaded from external source. So how to search for some text all over the WPF application?
First attempt: Reflection and AttachedProperties
My first attempt was to use attached properties. It looks like very good way to provide such functionality. I can “attach” my property to those controls, I want to search in and then, just test and compare string of well-known control in well-known property. For example if I want to search inside Text property of TextBox, I’ll use following syntax:
<TextBlock Name="tb" l:TextualSearch.IsEnabled="True" l:TextualSearch.SearchPath="Text" Text="Lorem ipsum d
Then in code-behind, I can test if it’s dependency or CLR property. We can use it, by using DependencyPropertyDescriptor
FrameworkElement fe = o as FrameworkElement;
if (fe != null && searchTargets.ContainsKey(fe))
{
Type tt = fe.GetType();
string pn = e.NewValue.ToString();
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromName(pn, tt, tt);
//this is Dependency property
if (dpd != null)
{
searchTargets[fe] = dpd.DependencyProperty;
}
//this is CRL property
else
{
searchTargets[fe] = tt.GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance).SingleOrDefault(p => p.Name == pn);
}
}
After we have all sources and all targets, we can attach to Text changed event externally
TextBox tb = o as TextBox;
if (tb != null)
{
if (!searchSources.Contains(tb) && ((bool)e.NewValue))
{
tb.TextChanged += OnSourceTextChanged;
searchSources.Add(tb);
}
else if (searchSources.Contains(tb) && !((bool)e.NewValue))
{
tb.TextChanged -= OnSourceTextChanged;
searchSources.Remove(tb);
}
}
And search
ICollection<FoundItem> results = new List<FoundItem>();
foreach (KeyValuePair<FrameworkElement, object> o in searchTargets)
{
object tso = null;
if (o.Value is DependencyProperty)
{
tso = o.Key.GetValue((DependencyProperty)o.Value);
}
else if(o.Value is PropertyInfo)
{
tso = ((PropertyInfo)o.Value).GetValue(o.Key,null);
}
if (tso is string && tso.ToString().Contains(text))
{
//got it!
FoundItem fe = new FoundItem(o.Key);
Rect cb = VisualTreeHelper.GetContentBounds(o.Key);
results.Add(fe);
}
else
{
//TODO: What can it be? FlowDocument, FixedDocument? Handle it!
}
But this is not very nice method and it have a lot of problems. For example, how I know what the coordinate of text I found. How to select it? How to treat all possible types of controls? We should try another way
Second attempt: Glyphs and Visuals
If you look into VisualTreeHelper, you’ll see GetDrawing method. It returns actual drawing, processed by WPF rendering engine. So, what WPF doing with text? Make it be fixed by using GlyphRuns inside GlyphRunVisual. So we can seek for all GlyphRuns in our application, enumerate it and search inside Characters array of the glyph to compare to required string. This methods looks much better, then the previous one. Let’s get all element in our application. In order to do it, we should enumerate all visuals in visual tree. Simple recursive method bring us flat list of all DependencyObjects in our visual tree
static void FillVisuals(DependencyObject current, ref List<DependencyObject> objects)
{
objects.Add(current);
int vcc = VisualTreeHelper.GetChildrenCount(current);for (int i = 0; i < vcc; ++i)
{
DependencyObject vc = VisualTreeHelper.GetChild(current, i);
FillVisuals(vc, ref objects);
}
}
Next, we have to get all Drawings and seek inside it for all GlyphRunDrawings
static List<GlyphRunVisual> GetAllGlyphsImp(FrameworkElement root)
{
List<GlyphRunVisual> glyphs = new List<GlyphRunVisual>();List<DependencyObject> objects = new List<DependencyObject>();
FillVisuals(root, ref objects);for (int i = 0; i < objects.Count; i++)
{
DrawingGroup dg = VisualTreeHelper.GetDrawing((Visual)objects[i]);
if (dg != null)
{
for (int j = 0; j < dg.Children.Count(); j++)
{
if (dg.Children[j] is DrawingGroup)
{
DrawingGroup idg = dg.Children[j] as DrawingGroup;
if (idg!= null)
{
for (int k = 0; k < idg.Children.Count(); k++)
{
if (idg.Children[k] is GlyphRunDrawing)
{glyphs.Add(new GlyphRunVisual((idg.Children[k] as GlyphRunDrawing).GlyphRun, (Visual)objects[i], (idg.Children[k] as GlyphRunDrawing).Bounds));
}
}
}
}
}
}
}return glyphs;
}
Now we have list of all Glyph runs together with their Drawings and Bounds. Actually, this is all we need in order to search and select text. How to do it? Simple. First get all chars of required string, then compare it with GlyphRun.Characters array to figure whether the required characters are exist in GlyphRun. After it, just build rectangle of found sequence and return it
public static List<Rect> SelectText(this List<GlyphRunVisual> glyphs, string text)
{
if (glyphs == null)
return null;
List<Rect> rects = new List<Rect>();
char[] chars = text.ToCharArray();
for (int i = 0; i < glyphs.Count; i++)
{
int offset = 0;
for (int c = offset; c < glyphs[i].GlyphRun.Characters.Count – offset – chars.Length; c++)
{
bool wasfound = true;
double width = 0;
CharacterHit ch = new CharacterHit();
for (int cc = 0; cc < chars.Length; cc++)
{
wasfound &= glyphs[i].GlyphRun.Characters[c + cc] == chars[cc];
width += glyphs[i].GlyphRun.AdvanceWidths[c + cc];
if(cc==0)
ch = new CharacterHit(c+cc,chars.Length);}
if (wasfound)
{Rect ab = glyphs[i].Bounds;
Rect box = new Rect(
glyphs[i].Visual.PointToScreen(new Point(glyphs[i].GlyphRun.GetDistanceFromCaretCharacterHit(ch), 0)),
new Size(ab.Width, ab.Height)
);box.Width = width;
rects.Add(box);
}
offset++;
}
}
return rects;
}
How, we have everything we need to select, so let’s create adorners to highlight found sequences
public class HighLightAdorner : Adorner
{
Brush b;
Pen p;
public HighLightAdorner(UIElement parent, Rect bounds) : base(parent) {
b = new SolidColorBrush(Colors.Yellow);
b.Opacity = .7;
p = new Pen(b, 1);
b.Freeze();
p.Freeze();
Bounds = bounds;
}public Rect Bounds
{
get { return (Rect)GetValue(BoundsProperty); }
set { SetValue(BoundsProperty, value); }
}
public static readonly DependencyProperty BoundsProperty =
DependencyProperty.Register("Bounds", typeof(Rect), typeof(HighLightAdorner), new UIPropertyMetadata(default(Rect)));protected override void OnRender(DrawingContext drawingContext)
{
drawingContext.DrawRectangle(b, p, Bounds);
}
}
And draw them on root panel
public static void DrawAdorners(this AdornerLayer al, UIElement parent, List<Rect> rects)
{
Adorner[] ads = al.GetAdorners(parent);
if (ads != null)
{
for (int i = 0; i < ads.Length; i++)
{
al.Remove(ads[i]);
}
}if (rects != null)
{
for (int i = 0; i < rects.Count; i++)
{
Rect rect = new Rect(parent.PointFromScreen(rects[i].TopLeft), parent.PointFromScreen(rects[i].BottomRight));
al.Add(new HighLightAdorner(parent, rect));
}
}
}
We done. Happy coding and be good people.
Source code for this article
May 12th, 2008 · Comments (15)
15 Responses to “Search and highlight any text on WPF rendered page”
Leave a Reply
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard




January 1st, 2009 at 12:47 am
Very clever solution, however what Will was asking was very relevant: if the text "ipsum dolor" wraps over two lines (due to word-wrapping, not explicit enter), your method will not highlight it. Ideally it would take into account all "pieces" of the text after wrapping and highlight them as well.
Furthermore, it didn’t seem to always find things that I typed even though I could plainly see them.
Nevertheless, I like your solution and will play around with it a bit and see if I can improve it.
I especially love how this can work with even simple controls like TextBox! Great job.
January 1st, 2009 at 12:47 am
Hi, Will
Q: What happens when the found text is wrapped in the middle?
A: It’s impossible scenario. You always search for full string
Q: And what if its outside the currently visible bounds of the control?
A: If it rendered by WPF (not virtualized), adorner will be added, but not visible
January 1st, 2009 at 12:47 am
Thanks for this post. I needed to know how to add "adorners" to controls for highlighting substrings within a control.
A couple questions about your code…
What happens when the found text is wrapped in the middle? And what if its outside the currently visible bounds of the control?
January 1st, 2009 at 12:47 am
You’ve been kicked (a good thing) – Trackback from DotNetKicks.com
January 17th, 2009 at 12:13 am
Hi
Great job, and for current time I think it’s unique.
Thanks
January 27th, 2009 at 1:37 am
err…which namespace is GlyphRunVisual in?
January 27th, 2009 at 6:35 am
System.Windows.Media
July 23rd, 2009 at 3:11 am
Why are the words not correctly highlighted? The words are not selected perfectly on the word bounds and it seems to select words that are not there.
October 27th, 2010 at 11:14 am
[...] was searching through world wide web and found some nice links like below:: http://khason.net/blog/search-and-highlight-any-text-on-wpf-rendered-page/ which states search and highlight any Text in WPF rendered page but it doesnt work when there are [...]
June 23rd, 2011 at 2:35 pm
Someone necessarily assist to make significantly posts I might state. That is the very first time I frequented your web page and to this point? I surprised with the analysis you made to make this particular submit extraordinary. Magnificent activity!
August 10th, 2011 at 12:37 pm
I’m using avalon edit as a text editor. I need to highlight multiple strings when searching for it.
Any idea how to apply your technique on it?
Thanks!
October 28th, 2011 at 7:39 pm
Pretty nice post. I simply stumbled upon your blog and wished to mention that I’ve really enjoyed browsing your weblog posts. In any case I will be subscribing on your rss feed and I am hoping you write again very soon!
December 10th, 2011 at 10:05 am
cheap with low price to take huge discount
March 7th, 2012 at 8:42 am
Nicely written write-up. You might be a really persuasive writer. I can see this inside your post.
September 19th, 2012 at 8:45 pm
[...] Search and highlight any text on WPF rendered page [...]