IME for C #

Source: Internet
Author: User
Tags wubi
C # IME

Although the input method is not a new thing, various language versions have, but in C # is not common; this will give a misunderstanding: C # can't do! In fact, C # can do it, the answer is yes-three ways: IMM, TSF and plug-in. IMM this is to tune some of Windows's underlying API, but in the new version of Windows is basically no longer available, is an obsolete mode of operation. TSF is a new approach recommended by Microsoft, but it is too small for C # data, and some of the main lines are for C + + versions, which can be used as a reference for the C # version. I mainly introduce a kind of plug-in (the day, the C # can write plug-ins? ), for the master is certainly insignificant, but also realized the plug-in and Input Method! Off-topic--c# can do plug-ins? The answer is yes, C # for Windows API programming material is still a lot of, the following is a brief introduction to the interface may be used to the API:

A hook was installed to intercept the mouse keyboard and other signals

Public static extern int SetWindowsHookEx (int idhook, HookProc lpfn, IntPtr HINSTANCE, int threadId);

Stop using hooks

Public static extern bool UnhookWindowsHookEx (int idhook);

< Span class= "Pl-en" > < Span class= "Pl-smi" > continue the next hook via the message hook

Public static extern int CallNextHookEx (int idhook, int nCode, Int32 WParam, IntPtr lParam);

Thread hooks need to be used

static extern int getcurrentthreadid ();

Use Windows API functions instead of getting the current instance function to prevent hooks from failing

Public static extern IntPtr getmodulehandle (string name);

Converts the specified virtual key code and the corresponding character or character of the keyboard state

public static extern int toascii (int uvirtkey,//[in] Specifies that the virtual key code be translated.
The key of the specified hardware scan code for int uscancode,//[in] must be translated into English. This value of the higher order bit sets the key, if yes (no pressure)
Byte[] lpbkeystate,//[in] pointer to a 256-byte array that contains the state of the current keyboard. An array of each element (byte) contains a key to the state. If the byte of the higher-order bit is a set, the key is down (pressed). At low bits, if the setting indicates that the key is on the switch. In this function, only the elbow of the CAPS LOCK key is relevant. Num locks and SCROLL LOCK keys are ignored in the toggle state.
Byte[] Lpwtranskey,//[out] pointer to the buffer to receive translated characters or characters.
int fustate);

1. With the above APIs, it is possible to implement the monitoring or locking of the mouse and keyboard, etc., then install the hooks first:


   Install the keyboard hook public void Start ()        {                     if (Hkeyboardhook = = 0)            {                keyboardhookprocedure = new HookProc ( KEYBOARDHOOKPROC);                Hkeyboardhook = SetWindowsHookEx (Wh_keyboard_ll, Keyboardhookprocedure, GetModuleHandle (Process.GetCurrentProcess ( ). Mainmodule.modulename), 0);                If SetWindowsHookEx fails if                (Hkeyboardhook = = 0)                {                    Stop ();                    throw new Exception ("Install keyboard hook failed");}}}        

2. After the installation, the acquisition of the hook will be processed:


private int Keyboardhookproc (int nCode, Int32 wParam, IntPtr lParam) {//Listen for keyboard events if (NCode &G t;= 0 && WParam = = 0x0100) {keyboardhookstruct mykeyboardhookstruct = (keyboardhookstru                CT) marshal.ptrtostructure (LParam, typeof (Keyboardhookstruct)); #region Switch if (Mykeyboardhookstruct.vkcode = = 20 | | Mykeyboardhookstruct.vkcode = = 160 | |                Mykeyboardhookstruct.vkcode = = 161) {isLocked = isLocked? false:true; } #endregion #region if (isLocked) {if (                    isstarted && mykeyboardhookstruct.vkcode >= && mykeyboardhookstruct.vkcode <= 57) {var c = Int.} Parse (((char) mykeyboardhookstruct.vkcode).                        ToString ());                        Onspaced (c);                        IsStarted = false;  return 1;                  } if (isstarted && mykeyboardhookstruct.vkcode = = 8) {                        Onbacked ();                    return 1; } if ((Mykeyboardhookstruct.vkcode >= && mykeyboardhookstruct.vkcode <= 90) | | Mykeyboardhookstruct.vkcode = = +) {if (Mykeyboardhookstruct.vkcode >= &A mp;& Mykeyboardhookstruct.vkcode <=) {keys keyData = (keys) My                            Keyboardhookstruct.vkcode;                            KeyEventArgs e = new KeyEventArgs (keyData);                            Keyupevent (this, e);                        IsStarted = true; } if (Mykeyboardhookstruct.vkcode = =) {Onspac                            Ed (0);                        IsStarted = false;                      }  return 1;                } else return 0;        } #endregion} return CallNextHookEx (Hkeyboardhook, NCode, WParam, LParam); }

Some of the above figures, for the newly-started students are not a problem, a look at the key to understand what to do.

3. Stop the hook


1 public void Stop () 2         {3             bool Retkeyboard = TRUE; 4  5  6             if (Hkeyboardhook! = 0) 7             {8                 Retkey board = UnhookWindowsHookEx (Hkeyboardhook); 9                 hkeyboardhook = 0;10             }11             if (! ( Retkeyboard))                 -throw new Exception ("Unload hook failed!") ");         

4. Registering events


1 private void Wordboard_load (object sender, EventArgs e) 2         {3             Program.keyBordHook.KeyUpEvent + = Keybordhook_ Keyupevent;4             Program.keyBordHook.OnSpaced + = keybordhook_onspaced;5             Program.keyBordHook.OnBacked + = Keybordhook_onbacked;6         }

5. Display and convert according to the input content


1 private void Showcharatar () 2         {3             this.listView1.BeginInvoke (new Action () = 4             {5                 Label1. Text = keys; 6  7                 try 8                 {9                     this.listView1.Items.Clear (); ten                     var arr = cachehelper.get (keys);                     if (arr! = NULL) for                         (int i = 0; i < (arr). Length > 10? 9:arr. Length); i++)                             this.listView1.Items.Add ((i + 1) + "," + Arr[i]),                         }16                 }17                 catch18                 {19                     Label1. Text = keys = "";                 }21             });         

6. Display input


1 private void Keybordhook_keyupevent (object sender, KeyEventArgs e) 2         {3             keys + = E.keycode.tostring (). ToLower (); 4 this             . Showcharatar (); 5         }

7. Space on screen


1 private void keybordhook_onspaced (int choose) 2         {3             try 4             {5                 if (Cachehelper.containskey (keys)) 6                 {7                     if (choose > 0) 8                     {9                         choose = choose-1;10                     }11                     Program.keyBordHook.Send (cachehelper. Get (keys) [choose]);                     Label1. Text = "";                     this.listView1.Clear ();                 }16             }17             catch18             {             }21             keys = ""; 22         }

8. Send data to the activated input box


1 public void Send (String msg) 2         {3             if (!string). IsNullOrEmpty (msg)) 4             {5                 Stop (); 6                 sendkeys.send ("{right}" + msg); 7                 Start (); 8             }9         }

9.back Key Fallback


1 private void keybordhook_onbacked () 2         {3             if (!string). IsNullOrEmpty (keys)) 4             {5                 keys = keys. Substring (0, keys. LENGTH-1); 6             }7 this             . Showcharatar (); 8         }

Of course, there are other keys that can be used to refine more functions, such as the pagination of pinyin.

As for what wubi, pinyin will use Thesaurus to solve, which wubi relatively simple, pinyin is very complex, a variety of participle, Lenovo and so on. Here to Wubi-based, pinyin for single-fight to achieve the basic input function, so do not need any advanced algorithm, simple to use memorycache easy and efficient (interested can come to http://www.php.cn/perfect)

10. Key word Conversion


  1/***************************************************************************************************** 2 * This code is copyrighted by @wenli, All rights Reserved (C) 2015-2017 3 ***************************************************************** 4 * CLR Version: 4.0.30319.42000 5 * Unique ID: 8EBC884B-EE5F-45DE-8638-C054B832E0CE 6 * Machine Name Name: WENLI-PC 7 * Contact e-mail: wenguoli_520@qq.com 8 ************************************************************************ 9 * Project name: $projectname $10 * Namespace: Wenli.iem 11 * Class Name: Cachehelper 12 * creation time: 2017/3/3 16:1 8:14 13 * Creator: Wenli 14 * Create Description: 15 ************************************************************************************ /using System; the using System.Collections.Generic; Using System.IO; Using System.Linq; Using System.Runtime.Caching; Using System.Text; Using System.Windows.Forms;    Namespace Wenli.IEM.Helper 27 (public static class Cachehelper) {MemoryCache _wubicache = new MemoryCache ("Wubi"); static memorycache _pinyincache = NE W memorycache ("Pinyin");  Static Cachehelper (), {$ var path = Application.startuppath + "\\Win32\\world.dll"; var arr = file.readalllines (path); The. foreach (string item in arr) of the PNS {$ var key = Item. Substring (0, item. IndexOf ("")); The $ var value = Item. Substring (item. IndexOf ("") + 1); _wubicache.add (Key, (object) value, Datetimeoffset.maxvalue); *//* Path = Application.startuppath + "\\Win32\\pinyin.dll"; % arr = file.readalllines (path); A. foreach (string item in arr) is {$ var key = Item. Substring (0, item. IndexOf ("")); var value = Item. Substring (item. IndexOf ("") + 1); Wuyi _pinyincache.add (Key, OBject) value, Datetimeoffset.maxvalue); String[] Get (string key), * * (!strin G.isnullorempty (key)) (+/-) (+) (+) (var) str = string. Empty;                         Try + 64 (_wubicache.contains (key)) str = _wubicache[key]. ToString (); The (_) = {} Pinyincache.contains (key)) (str + = "+ _pinyincache[key]. ToString (); The!string (). IsNullOrEmpty (str)). {$ var arr = str. Split (new string[] {""}, Stringsplitoptions.removeemptyentries); A-Z for (int i = 0; i < arr. Length; i++) (arr[i). IndexOf ("*") >-1) {Bayi Arr[i] = arr[i]. Substring (0, Arr[i]. IndexOf ("*")); A. (+}), and the return null; The ContainsKey (string key), 94 if (_wubicache.cont Ains (key))-return true; if (_pinyincache.contains (key)) The return is true; 98 return false; }100 101 public static void Clear () 102 {103 _wubicache.dispose (); 104 GC . Collect (-1); 105}106}107}

To this a basic C # version of the plug-in method has been successfully completed, source address: http://www.php.cn/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.