1 class controlIme 2 { 3 //声明一些API函数 4 [DllImport("imm32.dll")] 5 public static extern IntPtr ImmGetContext(IntPtr Hwnd); 6 [DllImport("imm32.dll")] 7 public static extern bool ImmGetOpenStatus(IntPtr Himc); 8 [DllImport("imm32.dll")] 9 public static extern bool ImmSetOpenStatus(IntPtr Himc, bool b1); 10 [DllImport("imm32.dll")] 11 public static extern bool ImmGetConversionStatus(IntPtr Himc, ref int lp, ref int lp2); 12 [DllImport("imm32.dll")] 13 public static extern int ImmSimulateHotKey(IntPtr Hwnd, int lnHotkey); 14 public const int IME_CMODE_FULLSHAPE = 0x8; 15 public const int IME_CHOTKEY_SHAPE_TOGGLE = 0x11; 16 17 public static void SetIme(Control ctl) 18 { 19 ChangeControl(ctl); 20 } 21 22 private static void ChangeControl(Control ctl) 23 { 24 //在控件的Click事件中触发来调整输入法状态 25 ctl.Click += new EventHandler(ctl_Click); 26 } 27 28 //控件的Click处理程序 29 public static void ctl_Click(object sender, EventArgs e) 30 { 31 ChangeControlIState(sender); 32 } 33 private static void ChangeControlIState(object sender) 34 { 35 Control ctl = (Control)sender; 36 ChangeControlIState(ctl.Handle); 37 } 38 39 //检查输入法的全角半角状态 40 public static void ChangeControlIState(IntPtr h) 41 { 42 IntPtr HIme = ImmGetContext(h); 43 if (ImmGetOpenStatus(HIme)) //如果输入法处于打开状态 44 { 45 int iMode = 0; 46 int iSentence = 0; 47 bool bSuccess = ImmGetConversionStatus(HIme, ref iMode, ref iSentence); //检索输入法信息 48 if (bSuccess) 49 { 50 if ((iMode & IME_CMODE_FULLSHAPE) > 0) //如果是全角 51 { 52 iMode &= (~IME_CMODE_FULLSHAPE); 53 ImmSimulateHotKey(h, IME_CHOTKEY_SHAPE_TOGGLE); //转换成半角 54 } 55 else 56 { 57 ImmSimulateHotKey(h, IME_CHOTKEY_SHAPE_TOGGLE); //转换成全角 58 } 59 } 60 } 61 } 62 }
下面是窗体代码:
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 #region 加载窗体时,焦点默认处于TextBox1上 8 private void Form1_Load(object sender, EventArgs e) 9 { 10 textBox1.Focus(); 11 } 12 #endregion 13 14 #region 全角与半角互相切换 15 private void button1_Click(object sender, EventArgs e) 16 { 17 bool flag = false; 18 textBox1.Focus(); 19 controlIme.SetIme(textBox1); 20 controlIme.ctl_Click(textBox1, e); 21 textBox1.Focus(); 22 if (button1.Text == "半角") 23 { 24 button1.Text = "全角"; 25 flag = true; 26 } 27 if (flag == false) 28 { 29 if (button1.Text == "全角") 30 { 31 button1.Text = "半角"; 32 } 33 } 34 } 35 #endregion 36 }
效果图: