{"record":{"id":"60713be4cab33546","repo":"babalae/better-genshin-impact","slug":"virtualkeycodes-key","errorCode":null,"errorMessage":"键盘编码必须是VirtualKeyCodes枚举中的值，当前传入的 {key} 不合法","messagePattern":"键盘编码必须是VirtualKeyCodes枚举中的值，当前传入的 (.+?) 不合法","errorType":"validation","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"BetterGenshinImpact/Core/Script/Dependence/GlobalMethod.cs","lineNumber":145,"sourceCode":"                }\n                else\n                {\n                    Simulation.SendInput.Keyboard.KeyPress(vk);\n                }\n                \n                break;\n        }\n    }\n\n    private static User32.VK ToVk(string key)\n    {\n        try\n        {\n            return User32Helper.ToVk(key);\n        }\n        catch\n        {\n            throw new ArgumentException($\"键盘编码必须是VirtualKeyCodes枚举中的值，当前传入的 {key} 不合法\");\n        }\n    }\n\n    #endregion 键盘操作\n\n    #region 鼠标操作\n\n    private static int _gameWidth = 1920;\n    private static int _gameHeight = 1080;\n    private static double _dpi = 1;\n\n    public static void SetGameMetrics(int width, int height, double dpi = 1)\n    {\n        // 必须16:9 的分辨率\n        if (width * 9 != height * 16)\n        {\n            throw new ArgumentException(\"游戏分辨率必须是16:9的分辨率\");\n        }","sourceCodeStart":127,"sourceCodeEnd":163,"githubUrl":"https://github.com/babalae/better-genshin-impact/blob/a7cb36712dcb409be610257d877fcea3597e9d6b/BetterGenshinImpact/Core/Script/Dependence/GlobalMethod.cs#L127-L163","documentation":"Thrown by GlobalMethod.ToVk when the provided key string does not correspond to a valid User32.VK (VirtualKeyCodes) enum member. Internally, User32Helper.ToVk uppercases the key, prefixes it with \"VK_\" if missing, and calls Enum.Parse — so the string must match a Vanara User32.VK enum name (e.g., \"A\", \"VK_A\", \"F1\", \"VK_F1\", \"SPACE\", \"VK_SPACE\"). The catch block swallows the original exception and rethrows as a generic ArgumentException.","triggerScenarios":"Calling key press methods (KeyPress, KeyDown, KeyUp) via GlobalMethod with a key string that is not a valid Windows virtual-key enum name: typos like \"RETURN\" (correct: \"RETURN\" is valid but \"RETRUN\" is not), lowercase-only strings that don't match after uppercasing, or completely invalid names like \"KEY_A\" or \"ESC\" vs \"ESCAPE\".","commonSituations":"Script passes a key name from user config without validation. Confusion between different key-naming conventions (e.g., \"ENTER\" vs \"RETURN\", \"ESC\" vs \"ESCAPE\"). Using HTML key event names instead of Win32 VK enum names.","solutions":["Verify the key string against the Vanara User32.VK enum — valid examples: \"A\"-\"Z\", \"0\"-\"9\", \"F1\"-\"F24\", \"SPACE\", \"RETURN\", \"ESCAPE\", \"TAB\", \"SHIFT\", \"CONTROL\".","Add a pre-check using Enum.TryParse<User32.VK>(\"VK_\" + key.ToUpper(), out _) before calling.","Provide a curated whitelist of accepted key names in your script's input validation.","Note: the original exception from Enum.Parse is swallowed — debug by temporarily calling User32Helper.ToVk directly to see the real error."],"exampleFix":"// before\nGlobalMethod.KeyPress(\"RETRUN\"); // typo\n\n// after\nvar validKeys = new HashSet<string>(Enum.GetNames<User32.VK>());\nvar normalizedKey = key.ToUpper().StartsWith(\"VK_\") ? key.ToUpper() : \"VK_\" + key.ToUpper();\nif (!validKeys.Contains(normalizedKey))\n    throw new ArgumentException($\"Unknown key: {key}. Use VK enum names like A, SPACE, RETURN.\");\nGlobalMethod.KeyPress(key);","handlingStrategy":"validation","validationCode":"// Validate key against User32.VK enum before calling key methods\nusing Vanara.PInvoke;\nvar normalizedKey = key.ToUpperInvariant();\nif (!normalizedKey.StartsWith(\"VK_\"))\n    normalizedKey = \"VK_\" + normalizedKey;\nif (!Enum.TryParse<User32.VK>(normalizedKey, out _))\n    throw new ArgumentException($\"Invalid key: {key}. Must be a valid VK enum name (e.g. A, SPACE, RETURN, F1).\");\nGlobalMethod.KeyPress(key);","typeGuard":"// Type guard for valid virtual key names\nstatic bool IsValidVk(string key)\n{\n    var normalized = key.ToUpperInvariant();\n    if (!normalized.StartsWith(\"VK_\"))\n        normalized = \"VK_\" + normalized;\n    return Enum.TryParse<User32.VK>(normalized, out _);\n}","tryCatchPattern":"try\n{\n    GlobalMethod.KeyPress(key);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"VirtualKeyCodes\"))\n{\n    _logger.LogError(\"Invalid key name: {Key}. Use VK enum names like A, SPACE, RETURN, ESCAPE.\", key);\n}","preventionTips":["Maintain a curated list of commonly used VK names for script input.","Test key strings against the Vanara User32.VK enum before use.","Note that User32Helper.ToVk uppercases and prefixes with VK_ automatically.","Common valid names: A-Z, 0-9, F1-F24, SPACE, RETURN, ESCAPE, TAB, SHIFT, CONTROL, ALT."],"tags":["validation","keyboard","virtual-key","enum-parse","input-sanitization"],"backgroundTag":null,"analyzedSha":"a7cb36712dcb409be610257d877fcea3597e9d6b","analyzedAt":"2026-08-13T16:44:57.548Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}