从Powershell调用user32.dll中的keybd_event

时间:2015-08-24 19:47:02

标签: c# powershell

我正在努力防止屏幕保护程序被踢入。 我尝试过发送击键但他们都需要按标题抓取一个窗口。 如果桌面上没有打开的窗口,则无需抓取。

所以我找到了可能有用的东西,但我不是C#向导。 它基于Simulating a keypress AND keyrelease in another application?

下面的代码应该发送1但我遗漏了一些东西。在从Powershell调用新类型之前我没有错误。 在这工作之后,我想让它发送一个F15重置屏幕保护程序倒计时但不修改屏幕上的东西。 (但我必须首先通过发送1来爬行)

Add-Type @"
using System.Runtime.InteropServices;

namespace ConsoleApplication1 
{
    public static class PressKeyForMe 
    { 
        [DllImport("user32.dll")] 
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

        //public static void Main(string[] args)
        public static void Main()
        {            
            //This code will press and hold the '1' button for 3 secs, and then will release for 1 second
            //VK_F15 0x7E
            keybd_event((byte)0x31, (byte)0x02, 0, UIntPtr.Zero);
            Thread.Sleep(3000);

            keybd_event((byte)0x31, (byte)0x82, (uint)0x2, UIntPtr.Zero);
            Thread.Sleep(1000);
        }
    }

}
"@
cls

#all of these give me: Unable to find type
[void] [PressKeyForMe]::Main()
[void] [ConsoleApplication1]::PressKeyForMe()
[void] [PressKeyForMe.Main]
[void] [ConsoleApplication1.Main]
[void] [ConsoleApplication1.PressKeyForMe]::Main()

1 个答案:

答案 0 :(得分:0)

感谢Mathias修复上面的代码。我能够完成我的剧本!

对于好奇,下面是我如何获得F15关键的工作。 每隔几分钟就可以使用[ScreenSpender.PressKeyForMe]::Main()来保持屏幕保护程序。 感谢John Savard帮助解决键盘扫描码。

#The following is an attempt to prevent the SceenSaver from kicking-in during installation
#We call it using this
#[ScreenSpender.PressKeyForMe]::Main()

Add-Type @"
using System;
using System.Threading;
using System.Runtime.InteropServices;

namespace ScreenSpender 
{
    public static class PressKeyForMe 
    { 
        [DllImport("user32.dll")] 
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

        //public static void Main(string[] args)
        public static void Main()
        {
            //bScan = PS/2 scan code. (We happen to be using Set 1)
            // Make  = when you press the key
            // Break = when you release the key
            //VK_F15 0x7E
            //SC_F15 0x5D   (Scan code set 1) (or 0x64) (http://www.quadibloc.com/comp/scan.htm  - by John Savard)
            //private const int KEYEVENTF_KEYUP = 0x02;
            //This code will press and hold the 'F15' key for 250 Milliseconds, and then will release for 200 Milliseconds
            keybd_event((byte)0x7E, (byte)0x5D, 0, UIntPtr.Zero);
            Thread.Sleep(250);

            // Release for 200 Milliseconds
            keybd_event((byte)0x7E, (byte)0x5D, (uint)0x2, UIntPtr.Zero);
            Thread.Sleep(200);
        }
    }
}
"@
相关问题