search
HomeWeb Front-endPS TutorialImplementing Chinese input on a blank form under C# can implement a PS-like text tool

Realizing Chinese input on a blank form under C

#Keywords: PS-like text tool, Chinese input. Repeated interception of Chinese

##Recently I have been researching on making a PS-like text tool. I checked a lot of information and asked a lot of people. Finally, the hard work paid off. I finally got it. Write it out for everyone to discuss.

Open the input method on a blank form. In C#, the blank window is the same no matter what. The input method cannot be opened. Even if this.ImeMode= ImeMode.NoControl is set, the input method recording window cannot be opened. I went to the Microsoft Development Forum and asked some questions. Thanks to moderator Zhou Xuefeng and Riquel_Dong for their advice. I used the API. Function: ImmAssociateContext(IntPtr hWnd, IntPtr hIMC); Finally the input method is called up. Its function is to associate the input with the specified window.


The code is as follows:


f (m.Msg == WM_IME_SETCONTEXT && m.WParam.ToInt32() == 1)


{


##ImmAssociateContext(this.Handle, m_hImc);


}


##Now the input method can be called. But a new problem has arisen. How to get the words on the input method recording form.


When the input method is turned on to input text, the WM_IME_CHAR message will be sent. We can get the Chinese characters by processing this message


You can use the IMM function: ImmGetCompositionString(IntPtr hIMC, int dwIndex, StringBuilder lpBuf, int dwBufLen); to obtain the Chinese characters or NUICODE type characters entered on the typing form. Of course, we will not study them here. Nothing else. Let’s just talk about Chinese characters.


The code to extract characters is as follows:


case WM_IME_CHAR:

# int size = ImmGetCompositionString(m_hImc, GCS_COMPSTR, null, 0);

##                                                                                  size += sizeof(Char); m_hImc, GCS_RESULTSTR, str, size);

## sb.Append(str.ToString());


MessageBox.Show(str.ToString());


# intoText();// Print text


##       isShowChina = true;



##                                                                                                   . It seems to be done. After testing it, I found that the printed words are all repeated words. For example, if I enter "Serve the People", what prints out is "Serve the People, Serve the People." Oh my god, there is a problem. Where is it.


## I checked MSDN. There is this description of WM_IME_CHAR:


the WM_IME_CHAR message includes a double-byte character and the application passes this message to DefWindowProc


Is this a problem? That's where it comes in. It's a problem of sending messages twice.

After reading an online discussion, I came up with a solution: add Judgment


if (m.WParam.ToInt32() == PM_REMOVE)


{


}


Test. Finally there is no problem



Code post


using System;

using System.Collections.Generic;


using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Text;

using System.Windows.Forms;

using System.Runtime .InteropServices;

namespace WindowsApplication2

{

public partial class UserControl1 : UserControl


{

        IntPtr m_hImc;


        bool isShowChina = false;

        public const int WM_IME_SETCONTEXT = 0x0281;


        private const int WM_IME_CHAR = 0x0286;


        private const int WM_CHAR = 0x0102;


        private const int WM_IME_COMPOSITION = 0x010F;


        private const int GCS_COMPSTR = 0x0008;


        [DllImport("Imm32.dll")]

        public static extern IntPtr ImmGetContext(IntPtr hWnd);


        [DllImport("Imm32.dll")]

        public static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);


        [DllImport("imm32.dll")]

        static extern int ImmGetCompositionString(IntPtr hIMC, int dwIndex, StringBuilder  lpBuf, int dwBufLen);



        private int GCS_RESULTSTR = 0x0800;


        private const int HC_ACTION = 0;


       private const int PM_REMOVE  = 0x0001;



        StringBuilder sb = new StringBuilder();


        Font font = new Font("宋体", 14, FontStyle.Regular);

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

            if (m.Msg == WM_IME_SETCONTEXT && m.WParam.ToInt32() == 1)

            {

                ImmAssociateContext(this.Handle, m_hImc);

             

            }

            switch (m.Msg)

            {

                case WM_CHAR:

                    KeyEventArgs e = new KeyEventArgs(((Keys)((int)((long)m.WParam))) | ModifierKeys);

                    char a = (char)e.KeyData; //英文

                    sb.Append(a);

                    intoText();

                    isShowChina = false;

                    break;

                case WM_IME_CHAR:


                    if (m.WParam.ToInt32() == PM_REMOVE) //如果不做这个判断.会打印出重复的中文

                    {

                        StringBuilder str = new StringBuilder();

                        int size = ImmGetCompositionString(m_hImc, GCS_COMPSTR, null, 0);

                        size += sizeof(Char);

                        ImmGetCompositionString(m_hImc, GCS_RESULTSTR, str, size);

                        sb.Append(str.ToString());

                        MessageBox.Show(str.ToString());

                        intoText();

                              isShowChina = true;                                                                                                          

#                                                                                                                                                                                                                                                                                                       

##                                                        Graphics g = this.CreateGraphics();

                                                                          Graphics g = this.CreateGraphics();

                       g.DrawString(sb.ToString(), font, Brushes.Black, 10, 10);

}

}

}

Even To realize Chinese input on a blank form under multiple C#, you can realize a PS-like text tool. For related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Photoshop for Designers: Creating Visual ConceptsPhotoshop for Designers: Creating Visual ConceptsApr 13, 2025 am 12:09 AM

Creating visual concepts in Photoshop can be achieved through the following steps: 1. Create a new document, 2. Add a background layer, 3. Use the brush tool to draw basic shapes, 4. Adjust colors and brightness, 5. Add text and graphics, 6. Use masks for local editing, 7. Apply filter effects, these steps help designers build a complete visual work from scratch.

Is Photoshop Free? Understanding Subscription PlansIs Photoshop Free? Understanding Subscription PlansApr 12, 2025 am 12:11 AM

Photoshop is not free, but there are several ways to use it at low cost or free: 1. The free trial period is 7 days, and you can experience all functions during this period; 2. Student and teacher discounts can cut costs by half, and school proof is required; 3. The CreativeCloud package is suitable for professional users and includes a variety of Adobe tools; 4. PhotoshopElements and Lightroom are low-cost alternatives, with fewer functions but lower prices.

Photoshop's Value: Weighing the Cost Against Its FeaturesPhotoshop's Value: Weighing the Cost Against Its FeaturesApr 11, 2025 am 12:02 AM

Photoshop is worth the investment because it provides powerful features and a wide range of application scenarios. 1) Core functions include image editing, layer management, special effects production and color adjustment. 2) Suitable for professional designers and photographers, but amateurs may consider alternatives such as GIMP. 3) Subscribe to AdobeCreativeCloud can be used as needed to avoid high one-time spending.

The Core Purpose of Photoshop: Creative Image DesignThe Core Purpose of Photoshop: Creative Image DesignApr 10, 2025 am 09:29 AM

Photoshop’s core use in creative image design is its powerful functionality and flexibility. 1) It allows designers to transform creativity into visual reality through layers, masks and filters. 2) Basic usages include cropping, resizing and color correction. 3) Advanced usages such as layer styles, blend modes and smart objects can create complex effects. 4) Common mistakes include improper layer management and excessive use of filters, which can be solved by organizing layers and using filters reasonably. 5) Performance optimization and best practices include rational use of layers, regular saving of files, and using shortcut keys.

Photoshop for Web Design: Advanced Techniques for UI/UXPhotoshop for Web Design: Advanced Techniques for UI/UXApr 08, 2025 am 12:19 AM

Photoshop can be used in web design to create high-fidelity prototypes, design UI elements, and simulate user interactions. 1. Use layers, masks and smart objects for basic design. 2. Simulate user interaction through animation and timeline functions. 3. Use scripts to automate the design process and improve efficiency.

Newbie's article: Use the ps brush to add crack effects to the font (share)Newbie's article: Use the ps brush to add crack effects to the font (share)Apr 07, 2025 am 06:21 AM

In the previous article "Teaching you step by step to add printing effects to plate images using ps (Favorites)", I introduced a small trick to use ps to add printing effects to plate images using ps. The following article will introduce to you how to use the ps brush to add crack effects to the font. Let’s take a look at how to do it.

Photoshop Advanced Typography: Creating Stunning Text EffectsPhotoshop Advanced Typography: Creating Stunning Text EffectsApr 07, 2025 am 12:15 AM

In Photoshop, you can create text effects through layer styles and filters. 1. Create a new document and add text. 2. Apply layer styles such as shadows and outer glow. 3. Use filters such as wave effects and add bevel and relief effects. 4. Use masks to adjust the effect range and intensity to optimize the visual impact of the text effect.

How to cut picturesHow to cut picturesApr 06, 2025 pm 10:27 PM

Cutting is the process of removing the background part in the image and leaving the subject behind. Common cutout methods include: manual cutout: use image editing software to manually outline the edge of the subject. Automatic cutout: Use software to automatically identify the subject and separate it from the background. Use third-party cutout tools: use special tools to cut out images. Channel cutout: Use the channel of the image to segment and select channels with obvious differences from the subject color for operation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment