将击键发送到非前景Windows应用

时间:2019-06-14 09:01:18

标签: c# windows

我需要每隔X秒钟从网络摄像头捕获一次图像。最初,我使用Python使用OpenCV编写了一个脚本,但该脚本非常有效,因此,因为内置于摄像头应用程序中的Windows 10可以生成普通图像,所以我认为我将只编写一个程序,以便在后台运行时向其发送击键,因此我仍然可以使用计算机,起初我创建了一些东西,可以很好地发送密钥,但是却将它们发送到前台应用,这是不可接受的

我在Stackoverflow上跳了几个问题,但似乎没有一种方法能达到我想要的效果

代码:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace This_project
{
    class Program
    {
        [DllImport("User32.dll")]

        public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        static void Main(string[] args)
        {
            Process p = Process.Start("microsoft.windows.camera:");

            const uint WM_KEYDOWN = 0x100;
            const uint WM_KEYUP = 0x0101;
            IntPtr edit = p.MainWindowHandle;

            Thread.Sleep(2500);

            PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.Space), IntPtr.Zero);
            PostMessage(edit, WM_KEYUP, (IntPtr)(Keys.Space), IntPtr.Zero);
        }
    }
}

我对程序的期望是,即使所有内容都不在前景中,它也会打开相机应用程序并按空格键拍照。我收集到的代码也会在运行时抛出异常:Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Snap_webcam.Program.Main(String[] args) in C:\Users\username\source\repos\This project\This project\Program.cs:line 21这行代码说:IntPtr edit = p.MainWindowHandle;的目的是分配向哪个窗口发送击键,但它可能仅适用于桌面应用程序< / p>

0 个答案:

没有答案
相关问题