c#操作IME代码

34 篇文章 0 订阅


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);
}
}
}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值