我有这个C#代码,我想更改名为label1的标签的文本。当我使用这些函数来检测按下了什么键并从函数中更改label1.Text时,文本不变。如何从此函数中更改label1.Text?
private void Form1_Load(object sender, EventArgs e)
{
_hookID = SetHook(_proc);
label1.Font = new Font("Arial", 24, FontStyle.Bold);
}
private static const int WH_KEYBOARD_LL = 13;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private 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);
}
}
private delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP)
{
int vkCode = Marshal.ReadInt32(lParam);
Form1 f = new Form1();
f.label1.Text = "Changed Label"; //<-------------------- change label here
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc 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);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
答案 0 :(得分:0)
你有几个错误:
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private static IntPtr HookCallback(
你试图分配一些在静态类方法中运行之前不会存在的东西。那是行不通的;你需要做类似的事情:
private LowLevelKeyboardProc _proc;
private IntPtr _hookID;
private IntPtr HookCallback(...
private void Form1_Load(object sender, EventArgs e)
{
_proc = new LowLevelKeyboardProc(HookCallback);
_hookID = SetHook(_proc);
了解static
的含义,除非绝对必要,否则不要使用它。它并没有做你认为它做的事情。
下一步:
Form1 f = new Form1();
f.label1.Text = "Changed Label";
您正在创建表单的全新副本f
,更改副本中的标签,然后丢弃副本而不显示任何内容或对其执行任何操作。你想要这个:
label1.Text = "Changed Label";