有一点问题是用微软拼音输入时会有小黑框。(其实Win32空窗口程序也是一样的)
首先用ImmGetContext获取当前窗口的输入点,然后重写WndProc方法,在接收到WM_IME_SETCONTEXT消息且wParam=1(输入法启用)时调用ImmAssociateContext关联输入点。
这样有个问题是输入的中文是重复的,解决办法是截留WM_IME_CHAR,跳过.NET(不调用base.WndProc),直接交给Windows处理(调用this.DefWndProc)。
其实更简单的方法是在里面放一个Control控件(不是UserControl),然后设定Dock为Fill就行了。但是仍然要做截留WM_IME_CHAR的处理,否则还是会收到重复的按键事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
IntPtr m_hImc;
public const int WM_IME_SETCONTEXT = 0x0281;
public const int WM_IME_CHAR = 0x0286;
[DllImport("Imm32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
public Form1()
{
InitializeComponent();
m_hImc = ImmGetContext(this.Handle); // 获得窗口IMM32输入点
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_IME_SETCONTEXT && m.WParam.ToInt32() == 1)
{
base.WndProc(ref m);
ImmAssociateContext(this.Handle, m_hImc); // 关联IMM32输入点
}
else if (m.Msg == WM_IME_CHAR)
{
this.DefWndProc(ref m); // 消息直接传给Windows,阻止.NET重复截留WM_IME_CHAR
}
else
{
base.WndProc(ref m);
}
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
this.Text += e.KeyChar.ToString();
}
}
}