字段初始值设定项不能引用非静态字段,方法或属性

时间:2017-08-10 17:27:20

标签: c# static field initializer non-static

我在表单中有以下代码:

using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Media;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ScreenShots
{
    public partial class ScreenShotConfigurationForm : Form
    {

        // ----- some other stuff (code, methods, etc...) is placed in here -----

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private LowLevelKeyboardProc _proc = HookCallback; // <<<< This is the row that is causing the error
        private IntPtr _hookID = IntPtr.Zero;

        private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                if (vkCode == 44) // 44 is the key code of PrintScreen button
                {
                    MakeScreenShot();
                }
            }

            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private 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)]
        private extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]

        private extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private extern IntPtr GetModuleHandle(string lpModuleName);
    }
}

这在Microsoft C#2008上给出了以下错误:

字段初始值设定项无法引用非静态字段,方法或属性&nbsp; ScreenShots.ScreenShotConfigurationForm.HookCallback(int,System.IntPtr,System.IntPtr)&#39; < / p>

  1. 这是什么意思?
  2. 我该如何解决?
  3. 我看到的截图: enter image description here

0 个答案:

没有答案