This code uses the 'user32.dll' library to get the current foreground window, thread, and process IDs. It then retrieves the keyboard layout for the current thread and checks if it is already set to English (US) (LCID 1033). If not, it switches the input language to English (US) using the 'ActivateKeyboardLayout' function.

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

    [DllImport("user32.dll")]
    public static extern IntPtr GetKeyboardLayout(uint idThread);

    [DllImport("user32.dll")]
    public static extern IntPtr ActivateKeyboardLayout(IntPtr hkl, uint flags);

    static void Main(string[] args)
    {
        IntPtr foregroundWindow = GetForegroundWindow();
        uint processId;
        uint threadId = GetWindowThreadProcessId(foregroundWindow, out processId);
        IntPtr keyboardLayout = GetKeyboardLayout(threadId);

        // Check if the current input language is English (US)
        if (keyboardLayout.ToInt64() != 1033) // 1033 is the LCID for English (US)
        {
            IntPtr englishLayout = new IntPtr(1033);
            ActivateKeyboardLayout(englishLayout, 0);
        }

        Console.WriteLine("Input language switched to English (US)");
        Console.ReadLine();
    }
}

Note that this code only switches the input language for the active window. If you want to switch the input language system-wide, you may need to use additional Windows API functions or third-party libraries.

C# Switch Input Language to English

原文地址: https://www.cveoy.top/t/topic/9oZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录