using System.Text;
using System;
using System.Runtime.InteropServices;
namespace Whatever {
public class GetComposition {
[DllImport("imm32.dll")]
public static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll")]
public static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("Imm32.dll", CharSet = CharSet.Unicode)]
private static extern int ImmGetCompositionStringW(IntPtr hIMC, int dwIndex, byte[] lpBuf, int dwBufLen);
private const int GCS_COMPSTR = 8;
/// IntPtr handle is the handle to the textbox
public string CurrentCompStr(IntPtr handle) {
int readType = GCS_COMPSTR;
IntPtr hIMC = ImmGetContext(handle);
try {
int strLen = ImmGetCompositionStringW(hIMC, readType, null, 0);
if (strLen > 0) {
byte[] buffer = new byte[strLen];
ImmGetCompositionStringW(hIMC, readType, buffer, strLen);
return Encoding.Unicode.GetString(buffer);
} else {
return string.Empty;
}
} finally {
ImmReleaseContext(handle, hIMC);
}
}
}
}
另一种:
using System.Runtime.InteropServices;
public partial class UserControl1 : UserControl
{
IntPtr m_hImc;
public const int WM_IME_SETCONTEXT = 0x0281;
[DllImport("Imm32.dll")]
public static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll")]
public static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr
hIMC);
public UserControl1()
{
InitializeComponent();
}
private void UserControl1_Load(object sender, EventArgs e)
{
m_hImc = ImmGetContext(this.Handle);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
// the usercontrol will receive a WM_IME_SETCONTEXT message
when it gets focused and loses focus respectively
// when the usercontrol gets focused, the m.WParam is 1
// when the usercontrol loses focus, the m.WParam is 0
// only when the usercontrol gets focused, we need to call the
IMM function to associate itself to the default input context
if (m.Msg == WM_IME_SETCONTEXT && m.WParam.ToInt32() == 1)
{
ImmAssociateContext(this.Handle, m_hImc);
}
}
}