Skip to content

Instantly share code, notes, and snippets.

@zerda
Last active August 29, 2015 14:00
Show Gist options
  • Save zerda/11101521 to your computer and use it in GitHub Desktop.
Save zerda/11101521 to your computer and use it in GitHub Desktop.
检测输入法的输入状态
public class MainWindow {
/// <summary>
/// 输入法的输入框被打开,已有文本在内
/// </summary>
/// <returns>若有文本正在输入则为 true,否则为 false</returns>
private bool IsImeCompositionWindowOpened() {
var helper = new WindowInteropHelper(this);
var hImc = NativeMethods.ImmGetContext(helper.Handle);
const int readType = NativeMethods.GCS_COMPSTR;
try {
var opened = NativeMethods.ImmGetOpenStatus(hImc);
if(opened) {
return NativeMethods.ImmGetCompositionStringW(hImc, readType, null, 0) > 0;
}
return false;
} finally {
NativeMethods.ImmReleaseContext(helper.Handle, hImc);
}
}
}
using System;
using System.Runtime.InteropServices;
internal static class NativeMethods {
#region IME
[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")]
public static extern bool ImmGetOpenStatus(IntPtr hImc);
[DllImport("imm32.dll")]
public static extern bool ImmGetConversionStatus(IntPtr hImc, ref int conversion, ref int sentence);
[DllImport("Imm32.dll", CharSet = CharSet.Unicode)]
public static extern int ImmGetCompositionStringW(IntPtr hImc, int index, byte[] buffer, int bufferLen);
public const int IME_CMODE_ALPHANUMERIC = 0x0;
public const int IME_CMODE_NATIVE = 0x1;
public const int IME_CMODE_KATAKANA = 0x2;
public const int IME_CMODE_LANGUAGE = 0x3;
public const int IME_CMODE_FULLSHAPE = 0x8;
public const int IME_CMODE_ROMAN = 0x10;
public const int IME_CMODE_CHARCODE = 0x20;
public const int IME_CMODE_HANJACONVERT = 0x40;
public const int IME_CMODE_SOFTKBD = 0x80;
public const int IME_CMODE_NOCONVERSION = 0x100;
public const int IME_CMODE_EUDC = 0x200;
public const int IME_CMODE_SYMBOL = 0x400;
public const int GCS_COMPSTR = 8;
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment