作者:kean
原文地址:http://through-the-interface.typepad.com/through_the_interface/2011/07/modifying-autocad-tooltips-using-net.html
To continue on the theme established in the last post, today we’re going to go ahead and modify AutoCAD tooltips, prefixing them with a fixed string. This is the next step on the path to modifying them in a more meaningful way (to translate them into a different language, for instance).
Here’s some C# code that implements a command to prefix all AutoCAD tooltips with a silly string (“Kean says this command …“):
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows;
namespace PrefixTooltips
{
public class Commands
{
List<string> _handled = null;
[CommandMethod("PREFTT")]
public void PrefixTooltips()
{
Document doc =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
_handled = new List<string>();
const string prefix = "Kean says this command ";
Autodesk.Windows.ComponentManager.ToolTipOpened +=
(s, e) =>
{
Autodesk.Internal.Windows.ToolTip tt =
s as Autodesk.Internal.Windows.ToolTip;
if (tt != null)
{
Autodesk.Windows.RibbonToolTip rtt =
tt.Content as Autodesk.Windows.RibbonToolTip;
if (rtt == null)
{
// Basic tooltip
if (tt.Content is string)
{
string contents = (string)tt.Content;
if (!contents.StartsWith(prefix))
{
tt.Content = prefix + contents;
}
}
}
else
{
// Enhanced tooltips
if (rtt.Content is string)
{
string contents = (string)rtt.Content;
if (!_handled.Contains(rtt.Command))
{
rtt.Content = prefix + contents;
_handled.Add(rtt.Command);
if (rtt.ExpandedContent != null)
{
TextBlock tb = rtt.ExpandedContent as TextBlock;
if (tb != null)
{
tb.Text = prefix + tb.Text;
}
else
{
StackPanel sp =
rtt.ExpandedContent as StackPanel;
if (sp != null)
{
foreach (UIElement elem in sp.Children)
{
tb = elem as TextBlock;
if (tb != null)
{
tb.Text = prefix + tb.Text;
}
}
}
}
}
}
}
}
}
};
}
}
}
When we run the PREFTT command and hover over ribbon, toolbar or statusbar icons, we see our tooltips – and even their extended content – gets prefixed with our string:
We keep track of tooltips that have already been translated by adding their command-names to a list: we need some tracking mechanism to avoid modifying tooltips multiple times, but this isn’t really optimal (something a bit more intelligent would be better, as – for one thing – this mechanism doesn’t differentiate between toolbars and ribbonbars, which may have different tooltips). All the same, it works reasonably well to prove the concept. |