如何在PowerShell脚本中正确执行C#代码实现媒体播放/暂停?
Let's break down the key issues with your current implementation:
Private Methods Can't Be Called Externally: Your
button1_Clickmethods are markedprivate, which means PowerShell can't access them directly from outside the class. These methods are designed to trigger from UI button clicks, not manual invocation.Incomplete Key Simulation: The
keybd_eventfunction requires both a key down and key up event to properly simulate a media key press. Your code only sends the key down event, so the system doesn't register a full, valid key press.Typo in Constant Name: You have a typo in
KEYEVENTF_EXTENTEDKEY— it should beKEYEVENTF_EXTENDEDKEY.Instance Method Misuse: The button click methods are instance methods, meaning you'd need to create an instance of
Form1to use them (which is unnecessary here since you're not building a UI).
Here's a revised version that fixes all these issues. We'll create a simple static class with public methods to handle media key presses correctly:
Add-Type @' using System; using System.Runtime.InteropServices; namespace UniversalSandbox { public static class MediaKeys { // Corrected constant names and values private const int KEYEVENTF_EXTENDEDKEY = 0x0001; private const int KEYEVENTF_KEYUP = 0x0002; private const int VK_MEDIA_PLAY_PAUSE = 0xB3; private const int VK_MEDIA_PREV_TRACK = 0xB1; private const int VK_MEDIA_NEXT_TRACK = 0xB0; // Correct P/Invoke signature for keybd_event [DllImport("user32.dll")] private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); // Public static methods to trigger media actions public static void PlayPause() { SimulateKeyPress(VK_MEDIA_PLAY_PAUSE); } public static void PreviousTrack() { SimulateKeyPress(VK_MEDIA_PREV_TRACK); } public static void NextTrack() { SimulateKeyPress(VK_MEDIA_NEXT_TRACK); } // Helper method to send full key down + up events private static void SimulateKeyPress(byte keyCode) { // Send key down event keybd_event(keyCode, 0, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero); // Send key up event to complete the press keybd_event(keyCode, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, UIntPtr.Zero); } } } '@
Now you can call the static methods directly from PowerShell to control media playback:
# Toggle play/pause [UniversalSandbox.MediaKeys]::PlayPause() # Skip to previous track [UniversalSandbox.MediaKeys]::PreviousTrack() # Skip to next track [UniversalSandbox.MediaKeys]::NextTrack()
- This works by simulating physical media key presses, so it will work with any media player that responds to system-wide media key commands.
- If you still don't see a response, ensure your media player is either the active window or configured to listen for global media keys.
内容的提问来源于stack exchange,提问作者BananaMaster

