关键词';这';在静态属性、静态方法或静态字段初始值设定项中无效
本文关键字:静态 无效 静态方法 属性 关键词 字段 | 更新日期: 2023-09-27 18:27:03
我使用以下代码:
public partial class ThisAddIn
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static IntPtr hookId = IntPtr.Zero;
private delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
private static HookProcedure procedure = HookCallback;
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProcedure lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
hookId = SetHook(procedure);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
UnhookWindowsHookEx(hookId);
}
private static IntPtr SetHook(HookProcedure procedure)
{
using (Process process = Process.GetCurrentProcess())
using (ProcessModule module = process.MainModule)
return SetWindowsHookEx(WH_KEYBOARD_LL, procedure, GetModuleHandle(module.ModuleName), 0);
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int pointerCode = Marshal.ReadInt32(lParam);
string pressedKey = ((Keys)pointerCode).ToString();
//Do some sort of processing on key press
var thread = new Thread(() =>
{ MessageBox.Show(pressedKey);
if (pressedKey.Equals("Space") || pressedKey.Equals("Tab"))
{
***Word.Range rng = this.Application.ActiveDocument.Words.Last;
rng.Select();
rng.Copy();
String input = Clipboard.GetText(TextDataFormat.Text);
}
});
thread.Start();
}
return CallNextHookEx(hookId, nCode, wParam, lParam);
}
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
}
我收到以下标有***的行的错误:
错误1关键字"this"在静态属性中无效,static方法或静态字段初始值设定项。
请告知
HookCallback
静态方法中的this
关键字是一个问题:
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int pointerCode = Marshal.ReadInt32(lParam);
string pressedKey = ((Keys)pointerCode).ToString();
//Do some sort of processing on key press
var thread = new Thread(() =>
{ MessageBox.Show(pressedKey);
if (pressedKey.Equals("Space") || pressedKey.Equals("Tab"))
{
***Word.Range rng = this.Application.ActiveDocument.Words.Last;
rng.Select();
rng.Copy();
String input = Clipboard.GetText(TextDataFormat.Text);
}
});
thread.Start();
}
return CallNextHookEx(hookId, nCode, wParam, lParam);
}
如果Application.ActiveDocument
在静态上下文中不可用(即,如果前面没有this
,它就无法工作),则需要传入所需的值。