首页 > 解决方案 > Visual C# 在一天中的某个时间模拟 F12 按键

问题描述

我的朋友让我创建一个程序,在一天中的某个时间为他按 F12。

这是一个不寻常的请求,我想知道如何让 Visual C# 在某个时间发送 F12 请求。也许最好实现一个自动按 F12 并在任务调度程序中设置的程序?我不知道。

我认为理想的情况是让程序在后台运行并在特定时间按下键。我不知道如何指示 Visual C# 发送 F12 键。另外,我不知道如何设置在某些时候关闭。

有人可以帮助我或将我指向资源吗?

标签: c#

解决方案


您可能想使用keybd_event. 这是一个示例代码,说明了如何使用它。

using System;
using System.Threading;
using System.Runtime.InteropServices;

public class Program
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    public const int KEYEVENTF_EXTENDEDKEY = 0x0001; // key down flag
    public const int KEYEVENTF_KEYUP = 0x0002; // key up flag
    public const int F12 = 123; // F12 key code

    public static void Main()
    {
        const int hour = 4;
        const int min = 15;

        // Get DateTime at which the key is supposed to be pressed
        DateTime nextCertainTime = DateTime.Now.Date.AddHours(hour).AddMinutes(min);

        // If it is already too late for today, add 1 day (set to tomorrow)
        if (nextCertainTime < DateTime.Now)
        {
            nextCertainTime = nextCertainTime.AddDays(1);
        }

        // Calculate the remaining time
        TimeSpan remainingTime = nextCertainTime - DateTime.Now;

        // Wait until "certain time"
        Thread.Sleep((int)remainingTime.TotalMilliseconds);

        keybd_event(F12, 0, KEYEVENTF_EXTENDEDKEY, 0); // press F12 down
        keybd_event(F12, 0, KEYEVENTF_KEYUP, 0); // release F12
    }
}

如果您想重复执行此操作,只需将其放入循环中并在每次迭代中while (true)增加 1 天。nextCertainTime

使用Timer会更好,但设置起来并不容易。

或者,也可以使用SendKeys.Send()代替keybd_event,但按单个键有点过分。

System.Windows.Forms.SendKeys.Send("{F12}");

如果您决定使用任务计划程序,如另一个答案中所建议的那样,您不妨考虑使用比 C# 更合适的东西。

也许是一个 AHK 脚本,它可以像这样简单:

Send {F12}

推荐阅读