В обработчике события хука клавиатуры не вызывается ф-ция чтения из буфера
Код:
Key lastKey = Key.L;
void KListener_KeyDown(object sender, RawKeyEventArgs args)
{
if (lastKey == Key.LeftCtrl && args.Key == Key.C)
{
text.Text = translate();
}
lastKey = args.Key;
}
void KListener_KeyDown(object sender, RawKeyEventArgs args)
{
if (lastKey == Key.LeftCtrl && args.Key == Key.C)
{
text.Text = translate();
}
lastKey = args.Key;
}
Код:
public string translate()
{
string result = " ";
bool isFinded = false;
try
{
bool isFinish = false;
int index = 0;
string _word = (string)Clipboard.GetData(DataFormats.Text);
string line = " ";
string word = " " + _word + " ";
string[] lines = System.IO.File.ReadAllLines("aemuller.txt");
word = word.ToLower();
foreach (string _line in lines)
{
line = _line.ToLower();
if (!isFinded && !fSimb(line, word))
if (isFinish)
return result;
else
continue;
if (isFinded && line.IndexOf(" ") > -1)
if (!(bool)check.IsChecked)
return result;
else
isFinded = false;
if (isFinded)
result += _line;
if (!isFinded && line.IndexOf(word) > -1 && line.IndexOf(word) < 5)
{
++index;
if (index == 1)
result += index.ToString() + ") " + _line;
else
result += "\n\n " + index.ToString() + ") " + _line;
isFinded = true;
}
}
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
if(result == " ")
return "Слово не найдено!\n";
return result;
}
{
string result = " ";
bool isFinded = false;
try
{
bool isFinish = false;
int index = 0;
string _word = (string)Clipboard.GetData(DataFormats.Text);
string line = " ";
string word = " " + _word + " ";
string[] lines = System.IO.File.ReadAllLines("aemuller.txt");
word = word.ToLower();
foreach (string _line in lines)
{
line = _line.ToLower();
if (!isFinded && !fSimb(line, word))
if (isFinish)
return result;
else
continue;
if (isFinded && line.IndexOf(" ") > -1)
if (!(bool)check.IsChecked)
return result;
else
isFinded = false;
if (isFinded)
result += _line;
if (!isFinded && line.IndexOf(word) > -1 && line.IndexOf(word) < 5)
{
++index;
if (index == 1)
result += index.ToString() + ") " + _line;
else
result += "\n\n " + index.ToString() + ") " + _line;
isFinded = true;
}
}
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
if(result == " ")
return "Слово не найдено!\n";
return result;
}
И класс хука клавиатуры:
Код:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace WpfApplication2.keyboard
{
public class KeyboardListener : IDisposable
{
public KeyboardListener()
{
hookedLowLevelKeyboardProc = (InterceptKeys.LowLevelKeyboardProc)LowLevelKeyboardProc;
hookId = InterceptKeys.SetHook(hookedLowLevelKeyboardProc);
hookedKeyboardCallbackAsync = new KeyboardCallbackAsync(KeyboardListener_KeyboardCallbackAsync);
}
~KeyboardListener()
{
Dispose();
}
public event RawKeyEventHandler KeyDown;
public event RawKeyEventHandler KeyUp;
#region Inner workings
private IntPtr hookId = IntPtr.Zero;
private delegate void KeyboardCallbackAsync(InterceptKeys.KeyEvent keyEvent, int vkCode);
[MethodImpl(MethodImplOptions.NoInlining)]
private IntPtr LowLevelKeyboardProc(int nCode, UIntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
if (wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_KEYDOWN ||
wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_KEYUP ||
wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_SYSKEYDOWN ||
wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_SYSKEYUP)
hookedKeyboardCallbackAsync.BeginInvoke((InterceptKeys.KeyEvent)wParam.ToUInt32(), Marshal.ReadInt32(lParam), null, null);
return InterceptKeys.CallNextHookEx(hookId, nCode, wParam, lParam);
}
private KeyboardCallbackAsync hookedKeyboardCallbackAsync;
private InterceptKeys.LowLevelKeyboardProc hookedLowLevelKeyboardProc;
void KeyboardListener_KeyboardCallbackAsync(InterceptKeys.KeyEvent keyEvent, int vkCode)
{
switch (keyEvent)
{
// KeyDown events
case InterceptKeys.KeyEvent.WM_KEYDOWN:
if (KeyDown != null)
KeyDown(this, new RawKeyEventArgs(vkCode, false));
break;
case InterceptKeys.KeyEvent.WM_SYSKEYDOWN:
if (KeyDown != null)
KeyDown(this, new RawKeyEventArgs(vkCode, true));
break;
// KeyUp events
case InterceptKeys.KeyEvent.WM_KEYUP:
if (KeyUp != null)
KeyUp(this, new RawKeyEventArgs(vkCode, false));
break;
case InterceptKeys.KeyEvent.WM_SYSKEYUP:
if (KeyUp != null)
KeyUp(this, new RawKeyEventArgs(vkCode, true));
break;
default:
break;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
InterceptKeys.UnhookWindowsHookEx(hookId);
}
#endregion
}
public class RawKeyEventArgs : EventArgs
{
public int VKCode;
public Key Key;
public bool IsSysKey;
public RawKeyEventArgs(int VKCode, bool isSysKey)
{
this.VKCode = VKCode;
this.IsSysKey = isSysKey;
this.Key = System.Windows.Input.KeyInterop.KeyFromVirtualKey(19);
}
}
public delegate void RawKeyEventHandler(object sender, RawKeyEventArgs args);
#region WINAPI Helper class
internal static class InterceptKeys
{
public delegate IntPtr LowLevelKeyboardProc(int nCode, UIntPtr wParam, IntPtr lParam);
public static int WH_KEYBOARD_LL = 13;
public enum KeyEvent : int
{
WM_KEYDOWN = 256,
WM_KEYUP = 257,
WM_SYSKEYUP = 261,
WM_SYSKEYDOWN = 260
}
public static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, UIntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
}
#endregion
}
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace WpfApplication2.keyboard
{
public class KeyboardListener : IDisposable
{
public KeyboardListener()
{
hookedLowLevelKeyboardProc = (InterceptKeys.LowLevelKeyboardProc)LowLevelKeyboardProc;
hookId = InterceptKeys.SetHook(hookedLowLevelKeyboardProc);
hookedKeyboardCallbackAsync = new KeyboardCallbackAsync(KeyboardListener_KeyboardCallbackAsync);
}
~KeyboardListener()
{
Dispose();
}
public event RawKeyEventHandler KeyDown;
public event RawKeyEventHandler KeyUp;
#region Inner workings
private IntPtr hookId = IntPtr.Zero;
private delegate void KeyboardCallbackAsync(InterceptKeys.KeyEvent keyEvent, int vkCode);
[MethodImpl(MethodImplOptions.NoInlining)]
private IntPtr LowLevelKeyboardProc(int nCode, UIntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
if (wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_KEYDOWN ||
wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_KEYUP ||
wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_SYSKEYDOWN ||
wParam.ToUInt32() == (int)InterceptKeys.KeyEvent.WM_SYSKEYUP)
hookedKeyboardCallbackAsync.BeginInvoke((InterceptKeys.KeyEvent)wParam.ToUInt32(), Marshal.ReadInt32(lParam), null, null);
return InterceptKeys.CallNextHookEx(hookId, nCode, wParam, lParam);
}
private KeyboardCallbackAsync hookedKeyboardCallbackAsync;
private InterceptKeys.LowLevelKeyboardProc hookedLowLevelKeyboardProc;
void KeyboardListener_KeyboardCallbackAsync(InterceptKeys.KeyEvent keyEvent, int vkCode)
{
switch (keyEvent)
{
// KeyDown events
case InterceptKeys.KeyEvent.WM_KEYDOWN:
if (KeyDown != null)
KeyDown(this, new RawKeyEventArgs(vkCode, false));
break;
case InterceptKeys.KeyEvent.WM_SYSKEYDOWN:
if (KeyDown != null)
KeyDown(this, new RawKeyEventArgs(vkCode, true));
break;
// KeyUp events
case InterceptKeys.KeyEvent.WM_KEYUP:
if (KeyUp != null)
KeyUp(this, new RawKeyEventArgs(vkCode, false));
break;
case InterceptKeys.KeyEvent.WM_SYSKEYUP:
if (KeyUp != null)
KeyUp(this, new RawKeyEventArgs(vkCode, true));
break;
default:
break;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
InterceptKeys.UnhookWindowsHookEx(hookId);
}
#endregion
}
public class RawKeyEventArgs : EventArgs
{
public int VKCode;
public Key Key;
public bool IsSysKey;
public RawKeyEventArgs(int VKCode, bool isSysKey)
{
this.VKCode = VKCode;
this.IsSysKey = isSysKey;
this.Key = System.Windows.Input.KeyInterop.KeyFromVirtualKey(19);
}
}
public delegate void RawKeyEventHandler(object sender, RawKeyEventArgs args);
#region WINAPI Helper class
internal static class InterceptKeys
{
public delegate IntPtr LowLevelKeyboardProc(int nCode, UIntPtr wParam, IntPtr lParam);
public static int WH_KEYBOARD_LL = 13;
public enum KeyEvent : int
{
WM_KEYDOWN = 256,
WM_KEYUP = 257,
WM_SYSKEYUP = 261,
WM_SYSKEYDOWN = 260
}
public static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, UIntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
}
#endregion
}
В пошаговой отладке, когда доходит до строки
Код:
string _word = (string)Clipboard.GetData(DataFormats.Text);
Так и не смог понять в чём дело, может быть кто-нибудь подскажет где ошибка?
это. Возможно в буфере обмена совсем не те данные, которые вы ожидаете.
Прочтите вначале
Текст исключения какой?
Цитата: Der Meister
Текст исключения какой?
"Текущий поток должен находиться в режиме контейнера с одним потоком (STA), чтобы вызовы OLE стали возможны."
Добавлял [STAThread], но пишет "Атрибут "STAThread" не допускается для этого типа объявления. Он допустим только для объявлений "method"."
Нет, в буфере те данные, я проверял.