WPF のネイティブ ブラウザー コントロールでは、カスタム コンテキスト メニューを設定できません。
さらに悪化します。マウスがブラウザー コンポーネント上にある間、またはフォーカスがある場合、入力によって生成されたイベントもキャッチされません。
これを回避するには、WindowsFormsHost 内で Windows フォーム ブラウザー コントロールを使用します。
まずWindows.Forms
、プロジェクト参照に追加します。
次に、次のようなことを行います。
XAML:
<Window x:Class="blarb.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<WindowsFormsHost Name="windowsFormsHost" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</Grid>
</Window>
C# コード:
public partial class MainWindow : Window
{
private System.Windows.Forms.WebBrowser Browser;
public MainWindow()
{
InitializeComponent();
//initialise the windows.forms browser component
Browser = new System.Windows.Forms.WebBrowser
{
//disable the default context menu
IsWebBrowserContextMenuEnabled = false
};
//make a custom context menu with items
System.Windows.Forms.ContextMenu BrowserContextMenu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem MenuItem = new System.Windows.Forms.MenuItem {Text = "Take Action"};
MenuItem.Click += MenuItemOnClick;
BrowserContextMenu.MenuItems.Add(MenuItem);
Browser.ContextMenu = BrowserContextMenu;
//put the browser control in the windows forms host
windowsFormsHost.Child = Browser;
//navigate the browser like this:
Browser.Navigate("http://www.google.com");
}
private void MenuItemOnClick(object sender, EventArgs eventArgs)
{
//will be called when you click the context menu item
}
}
ただし、これはまだ強調表示の方法を説明していません。
読み込みが完了したときにブラウザー コンポーネントによって発生するイベントをリッスンし、読み込まれたドキュメントの一部を置き換え、html コードを挿入して強調表示を行うことができます。
divs
状況によっては注意が必要な場合があることに注意してください (たとえば、 でテキストを選択する場合spans
などparagraphs
) 。