A family of Microsoft word processing software products for creating web, email, and print documents.
The outer focus of ElementHost will be interfering with IsInputMethodEnabled In ElementHost.
This problem may be improved by set IsInputMethodEnabled property when the text box got focus.
namespace WordAddIn1
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Tools.Ribbon;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Input;
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
if (Globals.ThisAddIn.CustomTaskPanes.Count != 0)
{
return;
}
var usercontrolForm = new System.Windows.Forms.UserControl();
var host = new System.Windows.Forms.Integration.ElementHost() { Dock = System.Windows.Forms.DockStyle.Fill };
usercontrolForm.Controls.Add(host);
StackPanel stack = new StackPanel();
for (int i = 0; i < 2; i++)
{
bool imeEnable = i == 1;
var textBox = new TextBox() { Margin = new Thickness(5), Text = $"Enabled={imeEnable}" };
ElementHostInputMethodTool.SetIsInputMethodEnabled(textBox, imeEnable);
stack.Children.Add(textBox);
}
var userControlWPF = new System.Windows.Controls.UserControl();
userControlWPF.Content = stack;
host.Child = userControlWPF;
var pane = Globals.ThisAddIn.CustomTaskPanes.Add(usercontrolForm, "Test");
pane.Visible = true;
}
}
class ElementHostInputMethodTool
{
public static bool GetIsInputMethodEnabled(System.Windows.Controls.Primitives.TextBoxBase obj)
{
return (bool)obj.GetValue(IsInputMethodEnabledProperty);
}
public static void SetIsInputMethodEnabled(System.Windows.Controls.Primitives.TextBoxBase obj, bool value)
{
obj.SetValue(IsInputMethodEnabledProperty, value);
}
public static readonly DependencyProperty IsInputMethodEnabledProperty =
DependencyProperty.RegisterAttached
("IsInputMethodEnabled"
, typeof(bool)
, typeof(ElementHostInputMethodTool)
, new PropertyMetadata(true, (sender, e) =>
{
var textBox = (System.Windows.Controls.Primitives.TextBoxBase)sender;
bool isEnable = (bool)e.NewValue;
if (isEnable)
{
textBox.GotKeyboardFocus -= TextBox_GotKeyboardFocus;
}
else
{
textBox.GotKeyboardFocus += TextBox_GotKeyboardFocus;
}
InputMethod.SetIsInputMethodEnabled(textBox, isEnable);
}));
private static void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = (System.Windows.Controls.Primitives.TextBoxBase)sender;
bool isImeEnable = GetIsInputMethodEnabled(textBox);
// set IsInputMethodEnabled property when got focus
InputMethod.SetIsInputMethodEnabled(textBox, isImeEnable);
}
}
}