Simulating Key Press c#

后端 未结 8 1426
青春惊慌失措
青春惊慌失措 2020-11-22 05:48

I want to simulate F5 key press in my c# program, When IE is open I want to be able refresh my website automatically.

8条回答
  •  我寻月下人不归
    2020-11-22 05:57

    Use mouse_event or keybd_event. They say not to use them anymore but you don't have to find the window at all.

    using System;
    using System.Runtime.InteropServices;
    
    public class SimulatePCControl
    {
    
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void keybd_event(uint bVk, uint bScan, uint dwFlags, uint dwExtraInfo);
    
    private const int VK_LEFT = 0x25;
    
    public static void LeftArrow()
    {
        keybd_event(VK_LEFT, 0, 0, 0);
    }
    
    }
    

    Virtual Key Codes are here for this one: http://www.kbdedit.com/manual/low_level_vk_list.html

    Also for mouse:

    using System.Runtime.InteropServices;
    using UnityEngine;
    
    public class SimulateMouseClick
    {
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
    //Mouse actions
    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;
    private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
    private const int MOUSEEVENTF_RIGHTUP = 0x10;
    
    public static void Click()
    {
        //Call the imported function with the cursor's current position
        uint X = (uint)0;
        uint Y = (uint)0;
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
        Debug.LogError("SIMULATED A MOUSE CLICK JUST NOW...");
    }
    
    //...other code needed for the application
    }
    

提交回复
热议问题