using System.Diagnostics;
以静默方式运行bat脚本
Console.WriteLine("同步执行");
Console.WriteLine(CMDHelper.CMDExecute("TimeStampVerificationCode.bat"));
Console.WriteLine("异步执行");
CMDHelper.CMDAsync("ipconfig2&TimeStampVerificationCode.bat&TimeStampVerificationCode.bat&TimeStampVerificationCode.bat");
/// <summary>
/// CMD帮助类
/// </summary>
public static class CMDHelper
{
/// <summary>
/// 直接执行cmd命令
/// </summary>
/// <param name="command"></param>
/// <param name="millisecond">等待进程结束的时间</param>
public static string CMDExecute(string command, int millisecond = 0)
{
if (string.IsNullOrEmpty(command))
{
return string.Empty;
}
string rslt = "";
// 双引号,确保调用程序路径中有空格时cmd命令执行成功
command = @"""" + command + @""" ";
using (Process p = new Process())
{
string dir = string.Empty;
if (Environment.Is64BitOperatingSystem)
{
dir = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative");
}
else
{
dir = Environment.GetFolderPath(Environment.SpecialFolder.System);
}
p.StartInfo.FileName = string.Format("{0}\cmd.exe", dir);
// 向cmd窗口直接写入命令,并关闭窗口
p.StartInfo.Arguments = " /C " + command;
// 不使用系统外壳程序启动
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
// 不创建窗口
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// 重定向输出,而不是默认的显示在dos控制台上
p.StartInfo.RedirectStandardOutput = true;
// 如果程序是管理员权限,那么运行cmd也是管理员权限
p.StartInfo.Verb = "runas";
try
{
p.Start();
if (millisecond == 0)
{
p.WaitForExit(); // 等待程序执行完退出进程 0表示成功
}
else
{
// 阻塞一定的时间;若到时间,将不产生阻塞
p.WaitForExit(millisecond);
}
rslt = p.StandardOutput.ReadToEnd();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return rslt;
}
/// <summary>
/// 异步执行cmd命令
/// </summary>
/// <param name="command"></param>
public static async void CMDAsync(string command)
{
if (string.IsNullOrEmpty(command))
{
return;
}
Action action = () =>
{
CMDAsyncImpl(command);
};
Func<Task> taskFunc = () =>
{
return Task.Run(() =>
{
action();
});
};
await taskFunc();
}
static void CMDAsyncImpl(string command)
{
Process p = new Process();
// 双引号,确保调用程序路径中有空格时cmd命令执行成功
command = @"""" + command + @""" ";
string dir = string.Empty;
if (Environment.Is64BitOperatingSystem)
{
dir = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative");
}
else
{
dir = Environment.GetFolderPath(Environment.SpecialFolder.System);
}
p.StartInfo.FileName = string.Format("{0}\cmd.exe", dir);
// 向cmd窗口直接写入命令,并关闭窗口
p.StartInfo.Arguments = " /C " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
SuccessInfo?.Invoke(e.Data);
}
};
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
ErrorInfo?.Invoke(e.Data);
}
};
p.EnableRaisingEvents = true;
p.Exited += (sender, e) =>
{
ExitedInfo?.Invoke();
};
try
{
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
catch (Exception ex)
{
string err = ex.Message;
p.StandardInput.WriteLine("exit");
return;
}
}
/// <summary>
/// 异步成功时执行的操作
/// </summary>
public static Action<string> SuccessInfo { get; set; }
/// <summary>
/// 异步错误时执行的操作
/// </summary>
public static Action<string> ErrorInfo { get; set; }
/// <summary>
/// 异步退出时执行的操作
/// </summary>
public static Action ExitedInfo { get; set; }
}
bat 生成时间戳验证码
@echo off
set "$=%temp%Spring"
>%$% Echo WScript.Echo((new Date()).getTime())
for /f %%a in ('cscript -nologo -e:jscript %$%') do set timestamp=%%a
del /f /q %$%
set n=2
setlocal enabledelayedexpansion
set str=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
for /l %%a in (1,1,%n%) do call :slz "%%a"
echo %random_str%%timestamp%
:slz
if "%~1"=="" goto:eof
set /a r=%random%%%52
set random_str=%random_str%!str:~%r%,1!
CMD嵌套控件
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
p.Start();
Thread.Sleep(100);
SetParent(p.MainWindowHandle, form1.Handle);
ShowWindow(p.MainWindowHandle, 3);
}
[DllImport("user32.dll", EntryPoint = "SetParent", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
与客户端交互
private void Button_Click(object sender, RoutedEventArgs e)
{
CMDHelper.SuccessInfo = SuccessInfo;
CMDHelper.ErrorInfo = ErrorInfo;
CMDHelper.ExitedInfo = ExitedInfo;
Stopwatch watch = new Stopwatch();
watch.Start();
CMDHelper.CMDAsync(txtCommand.Text.Trim());
lbTime.Text = "Time:" + watch.ElapsedMilliseconds + " ms";
}
StringBuilder _sbSuccess = new StringBuilder();
StringBuilder _sbError = new StringBuilder();
private void SuccessInfo(string msg)
{
_sbSuccess.AppendLine(msg);
txtReslt.OnUIThread(() =>
{
txtReslt.Text = _sbSuccess.ToString();
txtReslt.SelectionStart = txtReslt.Text.Length;
txtReslt.ScrollToEnd();
});
}
private void ErrorInfo(string msg)
{
_sbError.AppendLine(msg);
txtError.OnUIThread(() =>
{
txtError.Text = _sbError.ToString();
txtError.SelectionStart = txtError.Text.Length;
txtError.ScrollToEnd();
});
}
private void ExitedInfo()
{
_sbError.AppendLine("Success Exited! " + DateTime.Now.ToString());
txtError.OnUIThread(() =>
{
txtError.Text = _sbError.ToString();
txtError.SelectionStart = txtError.Text.Length;
txtError.ScrollToEnd();
});
}