Не срабатывает SendKeys при повторном нажатии горячих клавиш - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте, не срабатывает SendKeys при повторном нажатии горячих клавиш. Я понимаю, что дело в скорости обработки сообщений WinAPI, можно включить Thread.Sleep(300) , но это заметно тормозит выполнение программы и не дает решения ситуации т.к. может повторится если усердно нажимать гор.клав. Я пробовал использовать SendKeys через button - работает стабильно , но через хоты не получается, делал через свойство и метод - срабатывает один раз, ставил
Листинг программы
  1. void FocusedSelect()
  2. {
  3. bool state = RegisterHotKey(this.Handle, atom, 0x0002, 0x09);
  4. }
  5. protected override void WndProc(ref Message m)
  6. {
  7. if (m.Msg == 0x0312) //WM_HOTKEY
  8. {
  9. //Thread.Sleep(300);
  10.  
  11. //MessageBox.Show("TATATATTA");
  12. handle = GetForegroundWindow();
  13. SendKeys.Send("HeLlo!!!");
  14. SendKeys.SendWait("HeLlo!!!");
  15. UnregisterHotKey(this.Handle, atom);
  16. GlobalDeleteAtom(atom);
  17. FocusedSelect();
  18.  
  19. }
  20. base.WndProc(ref m);
  21.  
  22. }
Наврное смешно и тоже срабатывает только один раз. Делал через событие т.е нажимаю гор.клав. срабатывает событие включается обработчик и SendKeys но результат тот же. Охраняемый блок тоже не помогает Исключения не выдает. Подскжите направление. вот код
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Runtime.InteropServices;
  10. using System.Diagnostics;
  11. using System.Threading;
  12.  
  13. namespace EmulatorKey
  14. {
  15. public partial class Form1 : Form
  16. {
  17. [DllImport("user32.dll")]
  18. static extern IntPtr GetFocus();
  19. [DllImport("user32.dll")]
  20. public static extern IntPtr GetForegroundWindow();
  21. [DllImport("user32.dll")]
  22. public static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  23. [DllImport("User32.dll")]
  24. public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
  25. [DllImport("User32.dll")]
  26. public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
  27. [DllImport("kernel32.dll")]
  28. public static extern Int16 GlobalAddAtom(string name);
  29. [DllImport("kernel32.dll")]
  30. public static extern Int16 GlobalDeleteAtom(Int16 nAtom);
  31. [DllImport("user32.dll")]
  32. public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
  33. Int16 atom = GlobalAddAtom("PFight");
  34. // IntPtr handle;
  35. // int count = 0;
  36. // public delegate void CarDelegate(IntPtr Hnd);
  37. // public static event CarDelegate MaxSpeed;
  38. public Form1()
  39. {
  40. bool state = RegisterHotKey(this.Handle, atom, 0x0002, 0x09);
  41. InitializeComponent();
  42. this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
  43. //Form1.MaxSpeed += new CarDelegate(FocusedSelect);
  44. }
  45. void FocusedSelect()
  46. {
  47. //MessageBox.Show("TATATATTA");
  48. // SetForegroundWindow(handle);
  49. //SendKeys.SendWait("Hello!!!");
  50. }
  51. void Form1_FormClosing(object sender, FormClosingEventArgs e)
  52. {
  53. UnregisterHotKey(this.Handle, atom);
  54. GlobalDeleteAtom(atom);
  55. }
  56.  
  57. [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
  58.  
  59. protected override void WndProc(ref Message m)
  60. {
  61. if (m.Msg == 0x0312) //WM_HOTKEY
  62. {
  63. //Thread.Sleep(300);
  64.  
  65. //MessageBox.Show("TATATATTA");
  66. handle = GetForegroundWindow();
  67. // SetForegroundWindow(handle);
  68. //MaxSpeed(handle);
  69. SendKeys.Send("HeLlo!!!");
  70. SendKeys.SendWait("HeLlo!!!");
  71.  
  72. count++;
  73.  
  74. }
  75. base.WndProc(ref m);
  76.  
  77. }
  78. public IntPtr GetHandle()
  79. {
  80. return handle;
  81. }
  82. private void button1_Click(object sender, EventArgs e)
  83. {
  84.  
  85. IntPtr Handle = GetHandle();
  86. SetForegroundWindow(Handle);
  87. SendKeys.SendWait("Hello!!!");
  88.  
  89. }
  90.  
  91. }
  92. }

Решение задачи: «Не срабатывает SendKeys при повторном нажатии горячих клавиш»

textual
Листинг программы
  1. using System;
  2. using System.ComponentModel;
  3. using System.Runtime.InteropServices;
  4. using System.Threading;
  5. using System.Windows.Forms;
  6.  
  7. namespace Translit
  8. {
  9.     public partial class Form1 : Form
  10.     {
  11.         [DllImport("User32.dll", SetLastError = true)]
  12.         [return: MarshalAs(UnmanagedType.Bool)]
  13.         public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
  14.  
  15.         [DllImport("User32.dll", SetLastError = true)]
  16.         [return: MarshalAs(UnmanagedType.Bool)]
  17.         public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
  18.  
  19.         [DllImport("kernel32.dll", SetLastError = true)]
  20.         public static extern ushort GlobalAddAtom(string name);
  21.  
  22.         [DllImport("kernel32.dll", SetLastError = true)]
  23.         public static extern ushort GlobalDeleteAtom(ushort nAtom);
  24.  
  25.         [DllImport("user32.dll", SetLastError = true)]
  26.         public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
  27.  
  28.         ushort atom;
  29.  
  30.         public Form1()
  31.         {
  32.             InitializeComponent();
  33.             atom = GlobalAddAtom("PFight");
  34.             if (!RegisterHotKey(this.Handle, atom, 0x0002, 0x9))//ctrl+tab
  35.                 throw new Win32Exception(Marshal.GetLastWin32Error());
  36.             this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
  37.         }
  38.  
  39.         void Form1_FormClosed(object sender, FormClosedEventArgs e)
  40.         {
  41.             UnregisterHotKey(this.Handle, atom);
  42.             GlobalDeleteAtom(atom);
  43.         }
  44.  
  45.         protected override void WndProc(ref Message m)
  46.         {
  47.             if (m.Msg == 0x0312)
  48.             {
  49.                 CopyEmul();
  50.                 Thread.Sleep(50);
  51.                 GetBuffer();
  52.                 ReChars();
  53.                 SetBuff();
  54.                 PasteEmul();
  55.             }
  56.             base.WndProc(ref m);
  57.         }
  58.         /// <summary>
  59.         /// Копируем в буфер выделенный текст
  60.         /// </summary>
  61.         void CopyEmul()
  62.         {
  63.             keybd_event(0x11 /* VK_CONTROL */, 0, 0, 0);
  64.             keybd_event((byte)'C', 0, 0, 0);
  65.             keybd_event((byte)'C', 0, 0x2 /* KEYEVENTF_KEYUP */, 0);
  66.             keybd_event(0x11, 0, 0x2, 0);
  67.         }
  68.         /// <summary>
  69.         /// Вставляем в буфер выделенный текст
  70.         /// </summary>
  71.  
  72.         void PasteEmul()
  73.         {
  74.             keybd_event(0x11 /* VK_CONTROL */, 0, 0, 0);
  75.             keybd_event((byte)'V', 0, 0, 0);
  76.             keybd_event((byte)'V', 0, 0x2 /* KEYEVENTF_KEYUP */, 0);
  77.             keybd_event(0x11, 0, 0x2, 0);
  78.         }
  79.         /// <summary>
  80.         /// Получение информации из буфера в переменную richTextBox1.Text
  81.         /// </summary>
  82.         void GetBuffer()
  83.         {
  84.             richTextBox1.Text = ClipboardApi.GetText(this.Handle);
  85.         }
  86.         /// <summary>
  87.         /// Замена символов в переменной richTextBox1.Text с русских на агл. и наоборот, результат в richTextBox1.Text
  88.         /// </summary>
  89.         void ReChars()
  90.         {
  91.             richTextBox1.Text = new Charsi(richTextBox1.Text).Coding();
  92.         }
  93.         /// <summary>
  94.         /// Вставка в буфер значения переменной richTextBox1.Text
  95.         /// </summary>
  96.         void SetBuff()
  97.         {
  98.             ClipboardApi.SetText(this.Handle, richTextBox1.Text);
  99.         }
  100.  
  101.         private void button1_Click ( object sender, EventArgs e ) {
  102.  
  103.         }
  104.     }
  105. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы