Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Add-Type -Language CSharp -ReferencedAssemblies @(
- "System.Windows.Forms",
- "System.Drawing"
- ) -TypeDefinition @"
- using System;
- using System.Drawing;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- using System.Globalization;
- public class KeyboardTrayApp : Form
- {
- NotifyIcon trayIcon;
- Timer timer;
- ContextMenuStrip menu;
- [DllImport("user32.dll")]
- private static extern IntPtr GetKeyboardLayout(uint idThread);
- [DllImport("user32.dll")]
- private static extern IntPtr GetForegroundWindow();
- [DllImport("user32.dll")]
- private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
- string lastLang = "";
- public KeyboardTrayApp()
- {
- ShowInTaskbar = false;
- WindowState = FormWindowState.Minimized;
- trayIcon = new NotifyIcon();
- trayIcon.Visible = true;
- menu = new ContextMenuStrip();
- menu.Items.Add("Exit", null, OnExit);
- trayIcon.ContextMenuStrip = menu;
- timer = new Timer();
- timer.Interval = 200; // Fast, but lightweight
- timer.Tick += PollLayout;
- timer.Start();
- PollLayout(null, null);
- }
- private void OnExit(object sender, EventArgs e)
- {
- trayIcon.Visible = false;
- timer.Stop();
- Application.Exit();
- }
- private void PollLayout(object sender, EventArgs e)
- {
- string lang = GetLayoutCode();
- if (lang == lastLang)
- return;
- lastLang = lang;
- trayIcon.Icon = CreateTextIcon(lang);
- trayIcon.Text = "Keyboard: " + lang;
- }
- private string GetLayoutCode()
- {
- IntPtr hwnd = GetForegroundWindow();
- if (hwnd == IntPtr.Zero)
- return "??";
- uint threadId = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
- IntPtr layout = GetKeyboardLayout(threadId);
- int langId = ((int)layout) & 0xFFFF;
- try
- {
- CultureInfo culture = CultureInfo.GetCultureInfo(langId);
- return culture.TwoLetterISOLanguageName.ToUpper();
- }
- catch
- {
- return "??";
- }
- }
- private Icon CreateTextIcon(string text)
- {
- Bitmap bmp = new Bitmap(16, 16);
- Graphics g = Graphics.FromImage(bmp);
- g.Clear(Color.Black);
- using (Font font = new Font("Segoe UI", 8, FontStyle.Bold))
- using (Brush brush = new SolidBrush(Color.White))
- {
- SizeF size = g.MeasureString(text, font);
- g.DrawString(text, font, brush,
- (16 - size.Width) / 2,
- (16 - size.Height) / 2);
- }
- return Icon.FromHandle(bmp.GetHicon());
- }
- }
- "@
- $app = New-Object KeyboardTrayApp
- [System.Windows.Forms.Application]::Run($app)
Advertisement
Add Comment
Please, Sign In to add comment