c# - Visual C# 在一天中的某个时间模拟 F12 按键
问题描述
我的朋友让我创建一个程序,在一天中的某个时间为他按 F12。
这是一个不寻常的请求,我想知道如何让 Visual C# 在某个时间发送 F12 请求。也许最好实现一个自动按 F12 并在任务调度程序中设置的程序?我不知道。
我认为理想的情况是让程序在后台运行并在特定时间按下键。我不知道如何指示 Visual C# 发送 F12 键。另外,我不知道如何设置在某些时候关闭。
有人可以帮助我或将我指向资源吗?
解决方案
您可能想使用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}
推荐阅读
- sql-server - 为什么 Azure SQL Server 连接器在插入行时询问我具有默认值的列的值?
- react-native - React Native Maps - 显示UserLocation不起作用
- angular - 将参数传递给Angular服务中的函数(可观察对象)?
- ag-grid - api.getSelectedNodes() 不参考网格配置
- c - 如何将 .gcda 文件内容传输到另一个文件中?
- c++ - windows 使用 long int 就像在 32 位机器中一样,而在 64 位
- r - (MICE) 具有时间因素的数据集的缺失数据插补(纵向数据)
- html - 基于内容的php echo span样式颜色
- angularjs - 使用 ng-pattern 匹配密码会在 HTML 中公开密码
- css - 如何保护 React 组件免受全局样式的影响?