[英]How to send keys started hidden CMD process
如何發送字符鍵到隱藏的CMD窗口? 我的代碼:
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public void SendText(IntPtr hwnd, string keys)
{
if (hwnd != IntPtr.Zero)
{
if (SetForegroundWindow(hwnd))
{
System.Windows.Forms.SendKeys.Send(keys);
}
}
}
Process p;
int pid;
開始隱藏過程:
private void button1_Click(object sender, EventArgs e)
{
p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
pid = p.Id;
}
發送密鑰:
private void button4_Click(object sender, EventArgs e)
{
var proc1 = Process.GetProcessById(pid);
SetForegroundWindow(proc1.Handle);
SendKeys.Send("q");
}
如何發送密鑰我的程序? (但是我的代碼從ffmpeg.exe開始並發送“ q”鍵進行停止編碼)謝謝。
我有一個相同的問題,使用ProcessWindowStyle.Minimized或ProcessWindowStyle.Normal,它可以正常工作。 似乎沒有辦法使用ProcessWindowStyle.Hidden來實現。
您無法將密鑰發送到非活動窗口,也無法激活隱藏窗口。
解決方法:改為隱藏窗口樣式。 您可以使它最小化,但仍然需要激活它以發送密鑰,因此您可以遍歷所有正在運行的進程以找到最小化的窗口,將其激活然后發送密鑰並再次使其最小化(前景)。
將這段代碼放入您的主代碼中:
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lp1, string lp2);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
這是為(p)流程准備的方法:
public void sendkeys(string data)
{
send = true;
Process s = Process.GetProcessById(p.Id);
while (s.ProcessName == p.ProcessName && send)
{
while (send)
{
IntPtr h = s.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait(data);
Thread.Sleep(1000);
send = false;
}
}
}
例如,發送q >>> sendKeys("q")
;
在創建隱藏進程期間,必須設置RedirectStandardInput = true
,否則您的進程將不接受傳入密鑰。
因此,如果您這樣創建流程:
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardInput = true
};
var process = Process.Start(startInfo);
您可以通過StandardInput
向此過程發送消息
if (!process.HasExited)
{
using (var streamWriter = process.StandardInput)
{
// write your message here
var message = "q";
streamWriter.WriteLine(message);
streamWriter.Close();
}
process.WaitForExit();
process.Close();
process.Dispose();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.