C # Implementation of Input method function instance code sharing (graphic)

Source: Internet
Author: User
Tags wubi
This paper mainly introduces the knowledge of C # Implementation of input method. Has a good reference value. Let's take a look at the little series.

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

Continue with the next hook through the information 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 it is (not pressed) 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 >= 0 && WParam = = 0x0100) {keyboardhookstruct mykeyboardhookstruct = (keyboardhookstruct) marshal.ptrtostructure (LParam, typeof (Keyb    oardhookstruct)); #region Switch if (Mykeyboardhookstruct.vkcode = = 20 | | Mykeyboardhookstruct.vkcode = = 160 | |    Mykeyboardhookstruct.vkcode = = 161) {isLocked = isLocked? false:true; } #endregion #region if (isLocked) {if (isstarted && mykeyboardhookstruct.vkcode >= &AMP;&A mp Mykeyboardhookstruct.vkcode <=) {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 >= && mykeyboardhookstruct.vkcode <= 90)       {Keys keyData = (keys) Mykeyboardhookstruct.vkcode;       KeyEventArgs e = new KeyEventArgs (keyData);       Keyupevent (this, e);      IsStarted = true;       } if (Mykeyboardhookstruct.vkcode = =) {onspaced (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


public void Stop ()  {   bool Retkeyboard = true;   if (Hkeyboardhook! = 0)   {    Retkeyboard = UnhookWindowsHookEx (hkeyboardhook);    Hkeyboardhook = 0;   }   if (! ( Retkeyboard))    throw new Exception ("Unload hook failed!") ");  }

4. Registering events


private void Wordboard_load (object sender, EventArgs e)   {    Program.keyBordHook.KeyUpEvent + = Keybordhook_ keyupevent;    Program.keyBordHook.OnSpaced + = keybordhook_onspaced;    Program.keyBordHook.OnBacked + = keybordhook_onbacked;   }

5. Display and convert according to the input content


private void Showcharatar ()  {   This.listView1.BeginInvoke (new Action () =   {    Label1. Text = keys;    Try    {     this.listView1.Items.Clear ();     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]);      }    }    Catch    {     Label1. Text = keys = "";})   );  }

6. Display input


private void Keybordhook_keyupevent (object sender, KeyEventArgs e)   {    keys + = E.keycode.tostring (). ToLower ();    This. Showcharatar ();   }

7. Space on screen


private void keybordhook_onspaced (int choose)  {   try   {    if (Cachehelper.containskey (keys))    {     if (choose > 0)     {      choose = choose-1;     }     Program.keyBordHook.Send (Cachehelper.get (keys) [choose]);     Label1. Text = "";     This.listView1.Clear ();    }   }   Catch   {   }   keys = "";  }

8. Send data to the activated input box


public void Send (String msg)  {   if (!string. IsNullOrEmpty (msg))   {    Stop ();    Sendkeys.send ("{right}" + msg);    Start ();   }  }

9.back Key Fallback


private void keybordhook_onbacked ()  {   if (!string. IsNullOrEmpty (keys))   {    keys = keys. Substring (0, keys. Length-1);   }   This. Showcharatar ();  }

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 Https://github.com/yswenli/Wenli.IEM perfect)

10. Key word Conversion


/***************************************************************************************************** * This code copyright @wenli all , All rights Reserved (C) 2015-2017******************************************************************************** * CLR version: 4.0.30319.42000 * Unique ID: 8EBC884B-EE5F-45DE-8638-C054B832E0CE * machine Name: WENLI-PC * Contact e-Mail: wenguoli_520@qq.com************************************************************************************* * Project Name: $projectname $ * Namespace: Wenli.iem * class Name: Cachehelper * creation time: 2017/3/3 16:18:14 * Creator: Wenli * Create Description: * * * * /using System; 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{public static class Cachehelper {static MemoryCache _wubicache =  New MemoryCache ("Wubi"); static MemoryCache _pinyincache = new MemoryCache ("PinYIn ");   Static Cachehelper () {var path = Application.startuppath + "\\Win32\\world.dll";   var arr = file.readalllines (path); foreach (string item in arr) {var key = Item. Substring (0, item.    IndexOf ("")); var value = Item. Substring (item.    IndexOf ("") + 1);   _wubicache.add (Key, (object) value, Datetimeoffset.maxvalue);   }//Path = Application.startuppath + "\\Win32\\pinyin.dll";   arr = file.readalllines (path); foreach (string item in arr) {var key = Item. Substring (0, item.    IndexOf ("")); var value = Item. Substring (item.    IndexOf ("") + 1);   _pinyincache.add (Key, (object) value, Datetimeoffset.maxvalue); }} public static string[] Get (string key) {if (!string. IsNullOrEmpty (key)) {var str = string.    Empty; try {if (_wubicache.contains (key)) str = _wubicache[key].    ToString (); } catch {} try {if (_pinyincache.contains (key)) str + = "" + _pinyincache[key].    ToString (); } catch {} if (!string. IsNullOrEmpty (STR)) {var arr = str.     Split (new string[] {""}, Stringsplitoptions.removeemptyentries); for (int i = 0; i < arr. Length; i++) {if (Arr[i]. IndexOf ("*") >-1) {arr[i] = Arr[i]. Substring (0, Arr[i].      IndexOf ("*"));    }} return arr;  }} return null;   public static bool ContainsKey (string key) {if (_wubicache.contains (key)) return true;   if (_pinyincache.contains (key)) return true;  return false;   } public static void Clear () {_wubicache.dispose (); Gc.  Collect (-1); } }}

To this a basic C # version of the plug-in method has been successfully completed

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.