Here are the examples of the csharp api System.Diagnostics.Process.Kill() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1416 Examples
19
Source : LocalSteamController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
private static void killSteam()
{
Process[] proc = Process.GetProcesses();
foreach (Process item in proc)
{
if (item.ProcessName.ToLower().Equals("steam") || item.ProcessName.Equals("gameOverlayui"))
{
item.Kill();
}
}
}
19
Source : ToolWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
private void killRunningProc()
{
if (runningProc.Count > 0)
{
foreach (var item in runningProc)
{
Process tempp = (Process)item;
try
{
tempp.Kill();
}
catch (Exception) { }
}
runningProc.Clear();
}
}
19
Source : Program.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
static void Main(string[] args)
{
Process apache=null, backend=null, sbmon=null;
List<Process> memcachedInsts = null;
appExePath = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
appWorkDir = Path.GetDirectoryName(appExePath);
CheckAdminRights();
var procList = Process.GetProcesses();
foreach (var proc in procList)
{
if (stricmp(proc.ProcessName, "httpd") == 0)
{
Log("Httpd still running");
apache = proc;
}
else if (stricmp(proc.ProcessName, "sozluk_backend") == 0)
{
Log("Backend process still running");
backend = proc;
}
else if (stricmp(proc.ProcessName, "sbmon") == 0)
{
Log("Sbmon still running");
sbmon = proc;
}
else if (stricmp(proc.ProcessName, "memcached") == 0)
{
Log("A memcached instance found");
if (memcachedInsts == null)
memcachedInsts = new List<Process>();
memcachedInsts.Add(proc);
}
}
if (apache == null)
{
Log("starting httpd");
Run(HttpdExePath,string.Empty);
}
if (backend==null)
{
if (sbmon != null)
{
Log("there is no backend but sbmon. Sbmon killing");
sbmon.Kill();
}
if (memcachedInsts!=null)
{
Log("There some memcached instances. Killing em");
foreach (var mcp in memcachedInsts)
{
mcp.Kill();
}
}
Log("Starting up backend");
Run(BackendExePath, string.Empty);
}
Console.ReadKey();
}
19
Source : HealthMonitor.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
private void Leave(bool kill)
{
if (this.process == null)
return;
Log.Info("Leaving monitoring from {0} ({1})", procType, pid);
this.process.EnableRaisingEvents = false;
this.process.Exited -= Process_Exited;
if (kill)
{
Log.Warning("Kill requested...");
this.process.Kill();
this.process.WaitForExit(1000);
}
this.process = null;
}
19
Source : Watchdog.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
private void KillList(IEnumerable<Process> processes)
{
foreach (var proc in processes)
{
Log.Info("Attempting to kill pid {0}", proc.Id);
try
{
proc.Kill();
}
catch (Exception e)
{
Log.Error(e.Message);
proc.Dispose();
continue;
}
if (!proc.WaitForExit(2000))
{
Log.Error("Pid: {0} cant be killed!", proc.Id);
}
proc.Dispose();
}
}
19
Source : MemcachedProcess.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public bool Kill()
{
this.process.Kill();
this.process.WaitForExit(5000);
if (this.process.HasExited)
{
if (_Processes.ContainsKey(this.process.Id))
_Processes.Remove(this.process.Id);
return true;
}
return false;
}
19
Source : Helper.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static void KillProcess(string name)
{
Process[] proc = Process.GetProcessesByName(name);
foreach (var p in proc)
{
try
{
p.Kill();
}
catch (Exception e)
{
Log.Verbose(e.Message);
}
}
}
19
Source : XnaToFnaExt.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static void KillIfAlive(this Process p) {
try {
if (!p?.HasExited ?? false) p.Kill();
} catch { }
}
19
Source : BuildWindow.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
static void KillAllProcesses()
{
foreach (GameLoopMode loopMode in Enum.GetValues(typeof(GameLoopMode)))
{
if (loopMode.Equals(GameLoopMode.Undefined))
continue;
var buildExe = GetBuildExe(loopMode);
var processName = Path.GetFileNameWithoutExtension(buildExe);
var processes = System.Diagnostics.Process.GetProcesses();
foreach (var process in processes)
{
if (process.HasExited)
continue;
try
{
if (process.ProcessName != null && process.ProcessName == processName)
{
process.Kill();
}
}
catch (InvalidOperationException)
{
}
}
}
}
19
Source : BuildUtils.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public static void KillAllProcesses()
{
foreach (GameLoopMode loopMode in Enum.GetValues(typeof(GameLoopMode)))
{
if (loopMode.Equals(GameLoopMode.Undefined))
continue;
var buildExe = GetBuildExe(loopMode);
var processName = Path.GetFileNameWithoutExtension(buildExe);
var processes = System.Diagnostics.Process.GetProcesses();
foreach (var process in processes)
{
if (process.HasExited)
continue;
try
{
if (process.ProcessName != null && process.ProcessName == processName)
{
process.Kill();
}
}
catch (InvalidOperationException)
{
}
}
}
}
19
Source : Form1.cs
with MIT License
from 2881099
with MIT License
from 2881099
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
var process = Process.GetCurrentProcess();
process.Kill();
}
19
Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private void KillProcess(Process p)
{
try
{
p.CloseMainWindow();
p.WaitForExit(100);
if (!p.HasExited)
{
p.Kill();
p.WaitForExit(100);
}
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
}
}
19
Source : PrivoxyHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private static void KillProcess(Process p)
{
try
{
p.CloseMainWindow();
p.WaitForExit(100);
if (!p.HasExited)
{
p.Kill();
p.WaitForExit(100);
}
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private void btnOK_Click(object sender, EventArgs e)
{
try
{
Process[] existing = Process.GetProcessesByName("v2rayN");
foreach (Process p in existing)
{
string path = p.MainModule.FileName;
if (path == GetPath("v2rayN.exe"))
{
p.Kill();
p.WaitForExit(100);
}
}
}
catch (Exception ex)
{
// Access may be denied without admin right. The user may not be an administrator.
showWarn("Failed to close v2rayN(关闭v2rayN失败).\n" +
"Close it manually, or the upgrade may fail.(请手动关闭正在运行的v2rayN,否则可能升级失败。\n\n" + ex.StackTrace);
}
StringBuilder sb = new StringBuilder();
try
{
if (!File.Exists(fileName))
{
if (File.Exists(defaultFilename))
{
fileName = defaultFilename;
}
else
{
showWarn("Upgrade Failed, File Not Exist(升级失败,文件不存在).");
return;
}
}
string thisAppOldFile = Application.ExecutablePath + ".tmp";
File.Delete(thisAppOldFile);
string startKey = "v2rayN/";
using (ZipArchive archive = ZipFile.OpenRead(fileName))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
try
{
if (entry.Length == 0)
{
continue;
}
string fullName = entry.FullName;
if (fullName.StartsWith(startKey))
{
fullName = fullName.Substring(startKey.Length, fullName.Length - startKey.Length);
}
if (Application.ExecutablePath.ToLower() == GetPath(fullName).ToLower())
{
File.Move(Application.ExecutablePath, thisAppOldFile);
}
string entryOuputPath = GetPath(fullName);
FileInfo fileInfo = new FileInfo(entryOuputPath);
fileInfo.Directory.Create();
entry.ExtractToFile(entryOuputPath, true);
}
catch (Exception ex)
{
sb.Append(ex.StackTrace);
}
}
}
}
catch (Exception ex)
{
showWarn("Upgrade Failed(升级失败)." + ex.StackTrace);
return;
}
if (sb.Length > 0)
{
showWarn("Upgrade Failed,Hold ctrl + c to copy to clipboard.\n" +
"(升级失败,按住ctrl+c可以复制到剪贴板)." + sb.ToString());
return;
}
Process.Start("v2rayN.exe");
MessageBox.Show("Upgrade successed(升级成功)", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
19
Source : ShellManager.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from a4004
public static int ExitProcess(Process proc)
{
for (int i = 1; i <= 3; i++)
{
Program.Debug("shellmgr", $"Waiting for {proc.ProcessName} (pid {proc.Id}) to exit. [{i} of 3]");
if (!proc.HasExited)
proc.WaitForExit(1000);
else
{
Program.Debug("shellmgr", $"{proc.ProcessName} has exited. Exit code: {proc.ExitCode}.", Event.Success);
return proc.ExitCode;
}
}
Program.Debug("shellmgr", "Exit timeout. Sending WM_CLOSE to the process.");
try
{
proc.CloseMainWindow();
proc.WaitForExit(2000);
if (proc.HasExited)
{
Program.Debug("shellmgr", $"{proc.ProcessName} has exited. Exit code: {proc.ExitCode}.", Event.Success);
return proc.ExitCode;
}
else
Program.Debug("shellmgr", "Failed to gracefully exit the process.");
}
catch (Exception ex)
{
Program.Debug("shellmgr", $"Failed to gracefully exit the process {ex.Message}.", Event.Warning);
}
Program.Debug("shellmgr", "Signalling the process to exit. (SIGINT)");
Program.Debug("shellmgr", "Attaching to process Console.");
if (NativeMethods.AttachConsole((uint)proc.Id))
{
Program.Debug("shellmgr", "Attached. Overriding CTRL handler.");
NativeMethods.SetConsoleCtrlHandler(null, true);
Program.Debug("shellmgr", "Sending SIGINT.");
NativeMethods.GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);
NativeMethods.GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);
Program.Debug("shellmgr", "Detaching from Console.");
NativeMethods.FreeConsole();
Program.Debug("shellmgr", "Waiting for exit.");
proc.WaitForExit(2000);
if (proc.HasExited)
NativeMethods.SetConsoleCtrlHandler(null, false);
}
proc.WaitForExit(1000);
if (proc.HasExited)
{
Program.Debug("shellmgr", $"{proc.ProcessName} has exited. Exit code: {proc.ExitCode}", Event.Success);
Program.Debug("shellmgr", "Restoring CTRL handler.");
return proc.ExitCode;
}
else
{
Program.Debug("shellmgr", $"Failed to shutdown the process (pid {proc.Id}).", Event.Warning);
Program.Debug("shellmgr", "Killing process.");
try
{
proc.Kill();
if (!proc.HasExited)
Program.Debug("shellmgr", "Failed to kill the process.", Event.Critical);
else
{
Program.Debug("shellmgr", $"{proc.ProcessName} (pid {proc.Id}) terminated with exit code {proc.ExitCode}.", Event.Warning);
return proc.ExitCode;
}
}
catch (Exception ex)
{
Program.Debug("shellmgr", $"Failed to kill the process. {ex.Message}.", Event.Critical);
}
return 0xDEAD;
}
}
19
Source : ProcessExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static async Task<ProcessResult> StartProcessAsync(this Process process, ProcessStartInfo startInfo, bool showDebug = false, CancellationToken cancellationToken = default)
{
Debug.replacedert(!startInfo.UseShellExecute, "Process Start Info must not use shell execution.");
Debug.replacedert(startInfo.RedirectStandardOutput, "Process Start Info must redirect standard output.");
Debug.replacedert(startInfo.RedirectStandardError, "Process Start Info must redirect standard errors.");
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
var processResult = new TaskCompletionSource<ProcessResult>();
var errorCodeResult = new TaskCompletionSource<string[]>();
var errorList = new List<string>();
var outputCodeResult = new TaskCompletionSource<string[]>();
var outputList = new List<string>();
process.Exited += OnProcessExited;
process.ErrorDataReceived += OnErrorDataReceived;
process.OutputDataReceived += OnOutputDataReceived;
async void OnProcessExited(object sender, EventArgs args)
{
processResult.TrySetResult(new ProcessResult(process.ExitCode, await errorCodeResult.Task, await outputCodeResult.Task));
process.Close();
process.Dispose();
}
void OnErrorDataReceived(object sender, DataReceivedEventArgs args)
{
if (args.Data != null)
{
errorList.Add(args.Data);
if (!showDebug)
{
return;
}
UnityEngine.Debug.LogError(args.Data);
}
else
{
errorCodeResult.TrySetResult(errorList.ToArray());
}
}
void OnOutputDataReceived(object sender, DataReceivedEventArgs args)
{
if (args.Data != null)
{
outputList.Add(args.Data);
if (!showDebug)
{
return;
}
UnityEngine.Debug.Log(args.Data);
}
else
{
outputCodeResult.TrySetResult(outputList.ToArray());
}
}
if (!process.Start())
{
if (showDebug)
{
UnityEngine.Debug.LogError("Failed to start process!");
}
processResult.TrySetResult(new ProcessResult(process.ExitCode, new[] { "Failed to start process!" }, null));
}
else
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
CancellationWatcher(process);
}
async void CancellationWatcher(Process _process)
{
await Task.Run(() =>
{
try
{
while (!_process.HasExited)
{
if (cancellationToken.IsCancellationRequested)
{
_process.Kill();
}
}
}
catch
{
// ignored
}
});
}
return await processResult.Task;
}
19
Source : OVRPlatformTool.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void OnGUI()
{
if (boldFoldoutStyle == null)
{
boldFoldoutStyle = new GUIStyle(EditorStyles.foldout);
boldFoldoutStyle.fontStyle = FontStyle.Bold;
}
EditorGUIUtility.labelWidth = DEFAULT_LABEL_WIDTH;
GUILayout.Label("OVR Platform Tool", EditorStyles.boldLabel);
this.replacedleContent.text = "OVR Platform Tool";
GUIContent TargetPlatformLabel = new GUIContent("Target Oculus Platform");
OVRPlatformToolSettings.TargetPlatform = (TargetPlatform)MakeEnumPopup(TargetPlatformLabel, OVRPlatformToolSettings.TargetPlatform);
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.None)
return;
SetOVRProjectConfig(OVRPlatformToolSettings.TargetPlatform);
SetDirtyOnGUIChange();
commandMenuScroll = EditorGUILayout.BeginScrollView(commandMenuScroll, GUILayout.Height(Screen.height / 2));
{
// Add the UI Form
EditorGUI.BeginChangeCheck();
GUILayout.Space(15.0f);
// App ID
GUIContent AppIDLabel = new GUIContent("Oculus Application ID [?]: ",
"This AppID will be used when uploading the build.");
OVRPlatformToolSettings.AppID = MakeTextBox(AppIDLabel, OVRPlatformToolSettings.AppID);
// App Token
GUIContent AppTokenLabel = new GUIContent("Oculus App Token [?]: ",
"You can get your app token from your app's Oculus API Dashboard.");
appToken = MakePreplacedwordBox(AppTokenLabel, appToken);
// Release Channel
GUIContent ReleaseChannelLabel = new GUIContent("Release Channel [?]: ",
"Specify the releaes channel of the new build, you can rereplacedign to other channels after upload.");
OVRPlatformToolSettings.ReleaseChannel = MakeTextBox(ReleaseChannelLabel, OVRPlatformToolSettings.ReleaseChannel);
// Releaes Note
GUIContent ReleaseNoteLabel = new GUIContent("Release Note: ");
OVRPlatformToolSettings.ReleaseNote = MakeTextBox(ReleaseNoteLabel, OVRPlatformToolSettings.ReleaseNote);
// Platform specific fields
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Rift)
{
GUIContent BuildDirLabel = new GUIContent("Rift Build Directory [?]: ",
"The full path to the directory containing your Rift build files.");
OVRPlatformToolSettings.RiftBuildDirectory = MakeFileDirectoryField(BuildDirLabel, OVRPlatformToolSettings.RiftBuildDirectory,
"Choose Rifle Build Directory");
GUIContent BuildVersionLabel = new GUIContent("Build Version [?]: ",
"The version number shown to users.");
OVRPlatformToolSettings.RiftBuildVersion = MakeTextBox(BuildVersionLabel, OVRPlatformToolSettings.RiftBuildVersion);
GUIContent LaunchFileLabel = new GUIContent("Launch File Path [?]: ",
"The full path to the executable that launches your app.");
OVRPlatformToolSettings.RiftLaunchFile = MakeFileDirectoryField(LaunchFileLabel, OVRPlatformToolSettings.RiftLaunchFile,
"Choose Launch File", true, "exe");
}
else
{
GUIContent ApkPathLabel = new GUIContent("Build APK File Path [?]: ",
"The full path to the APK file.");
OVRPlatformToolSettings.ApkBuildPath = MakeFileDirectoryField(ApkPathLabel, OVRPlatformToolSettings.ApkBuildPath,
"Choose APK File", true, "apk");
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Quest)
{
// Quest specific fields
}
}
showOptionalCommands = EditorGUILayout.Foldout(showOptionalCommands, "Optional Commands", boldFoldoutStyle);
if (showOptionalCommands)
{
IncrementIndent();
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Rift)
{
// Launch Parameters
GUIContent LaunchParamLabel = new GUIContent("Launch Parameters [?]: ",
"Specifies any arguments preplaceded to the launcher.");
OVRPlatformToolSettings.RiftLaunchParams = MakeTextBox(LaunchParamLabel, OVRPlatformToolSettings.RiftLaunchParams);
GUIContent FirewallExceptionLabel = new GUIContent("Firewall Exception [?]: ",
"Specifies if a Windows Firewall exception is required.");
OVRPlatformToolSettings.RiftFirewallException = MakeToggleBox(FirewallExceptionLabel, OVRPlatformToolSettings.RiftFirewallException);
GUIContent GamepadEmulationLabel = new GUIContent("Gamepad Emulation [?]: ",
"Specifies the type of gamepad emulation used by the Oculus Touch controllers.");
OVRPlatformToolSettings.RiftGamepadEmulation = (GamepadType)MakeEnumPopup(GamepadEmulationLabel, OVRPlatformToolSettings.RiftGamepadEmulation);
show2DCommands = EditorGUILayout.Foldout(show2DCommands, "2D", boldFoldoutStyle);
if (show2DCommands)
{
IncrementIndent();
// 2D Launch File
GUIContent LaunchFile2DLabel = new GUIContent("2D Launch File [?]: ",
"The full path to the executable that launches your app in 2D mode.");
OVRPlatformToolSettings.Rift2DLaunchFile = MakeFileDirectoryField(LaunchFile2DLabel, OVRPlatformToolSettings.Rift2DLaunchFile,
"Choose 2D Launch File", true, "exe");
// 2D Launch Parameters
GUIContent LaunchParam2DLabel = new GUIContent("2D Launch Parameters [?]: ",
"Specifies any arguments preplaceded to the launcher in 2D mode.");
OVRPlatformToolSettings.Rift2DLaunchParams = MakeTextBox(LaunchParam2DLabel, OVRPlatformToolSettings.Rift2DLaunchParams);
DecrementIndent();
}
showRedistCommands = EditorGUILayout.Foldout(showRedistCommands, "Redistributable Packages", boldFoldoutStyle);
if (showRedistCommands)
{
IncrementIndent();
for (int i = 0; i < OVRPlatformToolSettings.RiftRedistPackages.Count; i++)
{
GUIContent RedistPackageLabel = new GUIContent(OVRPlatformToolSettings.RiftRedistPackages[i].name);
OVRPlatformToolSettings.RiftRedistPackages[i].include = MakeToggleBox(RedistPackageLabel, OVRPlatformToolSettings.RiftRedistPackages[i].include);
}
DecrementIndent();
}
showExpansionFileCommands = EditorGUILayout.Foldout(showExpansionFileCommands, "Expansion Files", boldFoldoutStyle);
if (showExpansionFileCommands)
{
IncrementIndent();
// Language Pack Directory
GUIContent LanguagePackLabel = new GUIContent("Language Pack Directory [?]: ",
"The full path to the directory containing the language packs");
OVRPlatformToolSettings.LanguagePackDirectory = MakeFileDirectoryField(LanguagePackLabel, OVRPlatformToolSettings.LanguagePackDirectory,
"Choose Language Pack Directory");
}
}
else
{
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Quest)
{
// Quest specific optional fields
}
showExpansionFileCommands = EditorGUILayout.Foldout(showExpansionFileCommands, "Expansion Files", boldFoldoutStyle);
if (showExpansionFileCommands)
{
IncrementIndent();
// OBB File Path
GUIContent ObbPathLabel = new GUIContent("OBB File Path [?]: ",
"The full path to the OBB file.");
OVRPlatformToolSettings.ObbFilePath = MakeFileDirectoryField(ObbPathLabel, OVRPlatformToolSettings.ObbFilePath,
"Choose OBB File", true, "obb");
}
}
if (showExpansionFileCommands)
{
// replacedets Directory
GUIContent replacedetsDirLabel = new GUIContent("replacedets Directory [?]: ",
"The full path to the directory with DLCs for this build.");
string replacedetsDirectory = MakeFileDirectoryField(replacedetsDirLabel, OVRPlatformToolSettings.replacedetsDirectory,
"Choose replacedets Directory");
if (replacedetsDirectory != OVRPlatformToolSettings.replacedetsDirectory)
{
OVRPlatformToolSettings.replacedetsDirectory = replacedetsDirectory;
OVRPlatformToolSettings.replacedetConfigs.Clear();
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.replacedetsDirectory))
{
DirectoryInfo dirInfo = new DirectoryInfo(OVRPlatformToolSettings.replacedetsDirectory);
FileInfo[] replacedetFiles = dirInfo.GetFiles();
foreach (FileInfo f in replacedetFiles)
{
OVRPlatformToolSettings.replacedetConfigs.Add(new replacedetConfig(f.Name));
}
}
EditorUtility.SetDirty(OVRPlatformToolSettings.Instance);
}
// Display bordered replacedet configuration list
GUILayout.Space(3f);
Rect rect = GUILayoutUtility.GetRect(0, GetreplacedetConfigElementHeight() + (replacedET_CONFIG_BACKGROUND_PADDING * 2),
GUILayout.ExpandWidth(true));
rect.x += (EditorGUI.indentLevel * INDENT_SPACING + 5);
rect.width -= (EditorGUI.indentLevel * INDENT_SPACING + 10);
DrawreplacedetConfigList(rect);
DecrementIndent();
}
EditorGUI.indentLevel--;
}
if (EditorGUI.EndChangeCheck())
{
EditorUtility.SetDirty(OVRPlatformToolSettings.Instance);
}
}
EditorGUILayout.EndScrollView();
GUILayout.Space(SINGLE_LINE_SPACING);
GUILayout.FlexibleSpace();
// Run OVR Lint Option
EditorGUIUtility.labelWidth = DEFAULT_LABEL_WIDTH;
GUIContent RunOvrLintLabel = new GUIContent("Run OVR Lint (Recommended) [?]: ",
"Run OVR Lint tool to ensure project is optimized for performance and meets Oculus packaging requirement for publishing.");
OVRPlatformToolSettings.RunOvrLint = MakeToggleBox(RunOvrLintLabel, OVRPlatformToolSettings.RunOvrLint);
// Add an Upload button
GUI.enabled = !activeProcess;
GUIContent btnTxt = new GUIContent("Upload");
var rt = GUILayoutUtility.GetRect(btnTxt, GUI.skin.button, GUILayout.ExpandWidth(false));
var btnYPos = rt.center.y;
rt.center = new Vector2(EditorGUIUtility.currentViewWidth / 2 - rt.width / 2 - buttonPadding, btnYPos);
if (GUI.Button(rt, btnTxt, GUI.skin.button))
{
OVRPlugin.SendEvent("oculus_platform_tool", "upload");
OVRPlatformTool.log = string.Empty;
OnUpload(OVRPlatformToolSettings.TargetPlatform);
}
// Add a cancel button
GUI.enabled = activeProcess;
btnTxt = new GUIContent("Cancel");
rt = GUILayoutUtility.GetRect(btnTxt, GUI.skin.button, GUILayout.ExpandWidth(false));
rt.center = new Vector2(EditorGUIUtility.currentViewWidth / 2 + rt.width / 2 + buttonPadding, btnYPos);
if (GUI.Button(rt, btnTxt, GUI.skin.button))
{
if (EditorUtility.DisplayDialog("Cancel Upload Process", "Are you sure you want to cancel the upload process?", "Yes", "No"))
{
if (ovrPlatUtilProcess != null)
{
ovrPlatUtilProcess.Kill();
OVRPlatformTool.log += "Upload process was canceled\n";
}
}
}
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUILayout.Space(SINGLE_LINE_SPACING);
debugLogScroll = EditorGUILayout.BeginScrollView(debugLogScroll);
GUIStyle logBoxStyle = new GUIStyle();
logBoxStyle.margin.left = 5;
logBoxStyle.wordWrap = true;
logBoxStyle.normal.textColor = logBoxStyle.focused.textColor = EditorStyles.label.normal.textColor;
EditorGUILayout.SelectableLabel(OVRPlatformTool.log, logBoxStyle, GUILayout.Height(position.height - 30));
EditorGUILayout.EndScrollView();
}
19
Source : SystemUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
[SecurityCritical]
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
internal static void KillAllProcesses(string processName)
{
try
{
foreach (Process proc in Process.GetProcessesByName(processName))
{
proc.Kill();
}
}
catch (InvalidOperationException ex)
{
SCaddinsApp.WindowManager.ShowMessageBox("InvalidOperationException: " + ex.Message);
}
catch (NotSupportedException ex)
{
SCaddinsApp.WindowManager.ShowMessageBox("NotSupportedException: " + ex.Message);
}
catch (System.ComponentModel.Win32Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
19
Source : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
private void NixKillProcessTree()
{
try
{
if (_proc?.HasExited == false)
{
_proc?.Kill();
}
}
catch (InvalidOperationException ex)
{
Trace.Info("Ignore InvalidOperationException during Process.Kill().");
Trace.Info(ex.ToString());
}
}
19
Source : RunnerService.cs
with MIT License
from actions
with MIT License
from actions
private void SendCtrlSignalToRunnerListener(uint signal)
{
try
{
if (RunnerListener != null && !RunnerListener.HasExited)
{
// Try to let the runner process know that we are stopping
//Attach service process to console of Runner.Listener process. This is needed,
//because windows service doesn't use its own console.
if (AttachConsole((uint)RunnerListener.Id))
{
//Prevent main service process from stopping because of Ctrl + C event with SetConsoleCtrlHandler
SetConsoleCtrlHandler(null, true);
try
{
//Generate console event for current console with GenerateConsoleCtrlEvent (processGroupId should be zero)
GenerateConsoleCtrlEvent(signal, 0);
//Wait for the process to finish (give it up to 30 seconds)
RunnerListener.WaitForExit(30000);
}
finally
{
//Disconnect from console and restore Ctrl+C handling by main process
FreeConsole();
SetConsoleCtrlHandler(null, false);
}
}
// if runner is still running, kill it
if (!RunnerListener.HasExited)
{
RunnerListener.Kill();
}
}
}
catch (Exception exception)
{
// InvalidOperationException is thrown when there is no process replacedociated to the process object.
// There is no process to kill, Log the exception and shutdown the service.
// If we don't handle this here, the service get into a state where it can neither be stoped nor restarted (Error 1061)
WriteException(exception);
}
}
19
Source : JobExtension.cs
with MIT License
from actions
with MIT License
from actions
public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
{
Trace.Entering();
ArgUtil.NotNull(jobContext, nameof(jobContext));
// create a new timeline record node for 'Finalize job'
IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null, ActionRunStage.Post);
using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
{
try
{
context.Start();
context.Debug("Starting: Complete job");
Trace.Info("Initialize Env context");
#if OS_WINDOWS
var envContext = new DictionaryContextData();
#else
var envContext = new CaseSensitiveDictionaryContextData();
#endif
context.ExpressionValues["env"] = envContext;
foreach (var pair in context.Global.EnvironmentVariables)
{
envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
}
// Populate env context for each step
Trace.Info("Initialize steps context");
context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);
var templateEvaluator = context.ToPipelineTemplateEvaluator();
// Evaluate job outputs
if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
{
try
{
context.Output($"Evaluate and set job outputs");
// Populate env context for each step
Trace.Info("Initialize Env context for evaluating job outputs");
var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
foreach (var output in outputs)
{
if (string.IsNullOrEmpty(output.Value))
{
context.Debug($"Skip output '{output.Key}' since it's empty");
continue;
}
if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
{
context.Warning($"Skip output '{output.Key}' since it may contain secret.");
continue;
}
context.Output($"Set output '{output.Key}'");
jobContext.JobOutputs[output.Key] = output.Value;
}
}
catch (Exception ex)
{
context.Result = TaskResult.Failed;
context.Error($"Fail to evaluate job outputs");
context.Error(ex);
jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
}
}
// Evaluate environment data
if (jobContext.ActionsEnvironment?.Url != null && jobContext.ActionsEnvironment?.Url.Type != TokenType.Null)
{
try
{
context.Output($"Evaluate and set environment url");
var environmentUrlToken = templateEvaluator.EvaluateEnvironmentUrl(jobContext.ActionsEnvironment.Url, context.ExpressionValues, context.ExpressionFunctions);
var environmentUrl = environmentUrlToken.replacedertString("environment.url");
if (!string.Equals(environmentUrl.Value, HostContext.SecretMasker.MaskSecrets(environmentUrl.Value)))
{
context.Warning($"Skip setting environment url as environment '{jobContext.ActionsEnvironment.Name}' may contain secret.");
}
else
{
context.Output($"Evaluated environment url: {environmentUrl}");
jobContext.ActionsEnvironment.Url = environmentUrlToken;
}
}
catch (Exception ex)
{
context.Result = TaskResult.Failed;
context.Error($"Failed to evaluate environment url");
context.Error(ex);
jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
}
}
if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
{
Trace.Info("Support log upload starting.");
context.Output("Uploading runner diagnostic logs");
IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();
try
{
diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);
Trace.Info("Support log upload complete.");
context.Output("Completed runner diagnostic log upload");
}
catch (Exception ex)
{
// Log the error but make sure we continue gracefully.
Trace.Info("Error uploading support logs.");
context.Output("Error uploading runner diagnostic logs");
Trace.Error(ex);
}
}
if (_processCleanup)
{
context.Output("Cleaning up orphan processes");
// Only check environment variable for any process that doesn't run before we invoke our process.
Dictionary<int, Process> currentProcesses = SnapshotProcesses();
foreach (var proc in currentProcesses)
{
if (proc.Key == Process.GetCurrentProcess().Id)
{
// skip for current process.
continue;
}
if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
{
Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
}
else
{
Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");
string lookupId = null;
try
{
lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
}
catch (Exception ex)
{
Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
Trace.Verbose(ex.ToString());
}
if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
{
context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
try
{
proc.Value.Kill();
}
catch (Exception ex)
{
Trace.Error("Catch exception during orphan process cleanup.");
Trace.Error(ex);
}
}
}
}
}
if (_diskSpaceCheckTask != null)
{
_diskSpaceCheckToken.Cancel();
}
}
catch (Exception ex)
{
// Log and ignore the error from JobExtension finalization.
Trace.Error($"Caught exception from JobExtension finalization: {ex}");
context.Output(ex.Message);
}
finally
{
context.Debug("Finishing: Complete job");
context.Complete();
}
}
}
19
Source : ProcessExtensionL0.cs
with MIT License
from actions
with MIT License
from actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public async Task SuccessReadProcessEnv()
{
using (TestHostContext hc = new TestHostContext(this))
{
Tracing trace = hc.GetTrace();
string envName = Guid.NewGuid().ToString();
string envValue = Guid.NewGuid().ToString();
Process sleep = null;
try
{
#if OS_WINDOWS
string node = Path.Combine(TestUtil.GetSrcPath(), @"..\_layout\externals\node12\bin\node");
#else
string node = Path.Combine(TestUtil.GetSrcPath(), @"../_layout/externals/node12/bin/node");
hc.EnqueueInstance<IProcessInvoker>(new ProcessInvokerWrapper());
#endif
var startInfo = new ProcessStartInfo(node, "-e \"setTimeout(function(){{}}, 15 * 1000);\"");
startInfo.Environment[envName] = envValue;
sleep = Process.Start(startInfo);
var timeout = Process.GetProcessById(sleep.Id);
while (timeout == null)
{
await Task.Delay(500);
timeout = Process.GetProcessById(sleep.Id);
}
try
{
trace.Info($"Read env from {timeout.Id}");
var value = timeout.GetEnvironmentVariable(hc, envName);
if (string.Equals(value, envValue, StringComparison.OrdinalIgnoreCase))
{
trace.Info($"Find the env.");
return;
}
}
catch (Exception ex)
{
trace.Error(ex);
}
replacedert.True(false, "Fail to retrive process environment variable.");
}
finally
{
sleep?.Kill();
}
}
}
19
Source : ProcessExtensions.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
private static bool TryKill(this Process process)
{
// exceptions may be thrown for all kinds of reasons
// and the _same exception_ may be thrown for all kinds of reasons
// System.Diagnostics.Process is "fine"
try
{
process.Kill();
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception)
#pragma warning restore CA1031 // Do not catch general exception types
{
return false;
}
return true;
}
19
Source : UpdateManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
public async Task StopAsync()
{
if (_hubConnection != null)
{
if (_hubConnection.State == HubConnectionState.Connected)
{
await _hubConnection.SendAsync("DisconnectIde", _ideId.ToString());
await Task.Delay(300);
await _hubConnection.StopAsync();
}
}
foreach (var p in new[] { _pServer })
{
if (p is null)
continue;
if (p.HasExited)
continue;
p.Kill();
p.Close();
p.Dispose();
}
_pServer = null;
// Ensure processes are killed
KillRunningProcesses();
}
19
Source : UpdateManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
private void KillRunningProcesses()
{
if (File.Exists(_processDatFilePath))
{
using (var s = File.OpenText(_processDatFilePath))
{
int processId = 0;
try
{
while(!s.EndOfStream)
{
processId = Int32.Parse(s.ReadLine());
if (processId == 0)
continue;
var process = Process.GetProcessById(processId);
if (process != null && !process.HasExited)
process.Kill();
}
}
catch (Exception ex)
{
if (processId != 0)
System.Diagnostics.Debug.WriteLine($"RealXaml was unable to kill process with id {processId}");
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
19
Source : LogCatWindow.cs
with MIT License
from adrenak
with MIT License
from adrenak
void OnGUI() {
GUILayout.BeginHorizontal();
// Enable pre-filter if process is not started
GUI.enabled = logCatProcess == null;
prefilterOnlyUnity = GUILayout.Toggle(prefilterOnlyUnity, "Only Unity", "Button", GUILayout.Width(80));
// Enable button if process is not started
GUI.enabled = logCatProcess == null;
if (GUILayout.Button("Start", GUILayout.Width(60))) {
// Start `adb logcat -c` to clear the log buffer
ProcessStartInfo clearProcessInfo = new ProcessStartInfo();
clearProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
clearProcessInfo.CreateNoWindow = true;
clearProcessInfo.UseShellExecute = false;
clearProcessInfo.FileName = EditorPrefs.GetString("AndroidSdkRoot") + "/platform-tools/adb";
clearProcessInfo.Arguments = @"logcat -c";
Process.Start(clearProcessInfo);
// Start `adb logcat` (with additional optional arguments) process for filtering
ProcessStartInfo logProcessInfo = new ProcessStartInfo();
logProcessInfo.CreateNoWindow = true;
logProcessInfo.UseShellExecute = false;
logProcessInfo.RedirectStandardOutput = true;
logProcessInfo.RedirectStandardError = true;
logProcessInfo.FileName = EditorPrefs.GetString("AndroidSdkRoot") + "/platform-tools/adb";
logProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
// Add additional -s argument for filtering by Unity tag.
logProcessInfo.Arguments = "logcat" + (prefilterOnlyUnity ? " -s \"Unity\"" : "");
logCatProcess = Process.Start(logProcessInfo);
logCatProcess.ErrorDataReceived += (sender, errorLine) => {
if (errorLine.Data != null && errorLine.Data.Length > 2)
AddLog(new LogCatLog(errorLine.Data));
};
logCatProcess.OutputDataReceived += (sender, outputLine) => {
if (outputLine.Data != null && outputLine.Data.Length > 2)
AddLog(new LogCatLog(outputLine.Data));
};
logCatProcess.BeginErrorReadLine();
logCatProcess.BeginOutputReadLine();
}
// Disable button if process is already started
GUI.enabled = logCatProcess != null;
if (GUILayout.Button("Stop", GUILayout.Width(60))) {
try {
logCatProcess.Kill();
}
catch (InvalidOperationException ex) {
// Just ignore it.
}
finally {
logCatProcess = null;
}
}
GUI.enabled = true;
if (GUILayout.Button("Clear", GUILayout.Width(60))) {
lock (logsList) {
logsList.Clear();
filteredList.Clear();
}
}
GUILayout.Label(filteredList.Count + " matching logs", GUILayout.Height(20));
// Create filters
filterByString = GUILayout.TextField(filterByString, GUILayout.Height(20));
GUI.color = new Color(0.75f, 0.5f, 0.5f, 1f);
filterOnlyError = GUILayout.Toggle(filterOnlyError, "Error", "Button", GUILayout.Width(80));
GUI.color = new Color(0.95f, 0.95f, 0.3f, 1f);
filterOnlyWarning = GUILayout.Toggle(filterOnlyWarning, "Warning", "Button", GUILayout.Width(80));
GUI.color = new Color(0.5f, 0.5f, 0.75f, 1f);
filterOnlyDebug = GUILayout.Toggle(filterOnlyDebug, "Debug", "Button", GUILayout.Width(80));
GUI.color = new Color(0.5f, 0.75f, 0.5f, 1f);
filterOnlyInfo = GUILayout.Toggle(filterOnlyInfo, "Info", "Button", GUILayout.Width(80));
GUI.color = Color.white;
filterOnlyVerbose = GUILayout.Toggle(filterOnlyVerbose, "Verbose", "Button", GUILayout.Width(80));
GUILayout.EndHorizontal();
GUIStyle lineStyle = new GUIStyle();
lineStyle.normal.background = MakeTexture(600, 1, new Color(1.0f, 1.0f, 1.0f, 0.1f));
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Height(Screen.height - 45));
// Show only top `showingLimit` log entries
int fromIndex = filteredList.Count - showLimit;
if (fromIndex < 0)
fromIndex = 0;
for (int i = fromIndex; i < filteredList.Count; i++) {
LogCatLog log = filteredList[i];
GUI.backgroundColor = log.GetBgColor();
GUILayout.BeginHorizontal(lineStyle);
GUILayout.Label(log.CreationDate + " | " + log.Message);
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
19
Source : DotnetRunFixture.cs
with MIT License
from AdrianWilczynski
with MIT License
from AdrianWilczynski
public void Dispose()
{
_process.CloseMainWindow();
if (!_process.WaitForExit(TimeSpan.FromSeconds(3).Milliseconds))
{
try { _process.Kill(); } catch { }
}
_process.Dispose();
}
19
Source : MemoryManager.cs
with GNU General Public License v3.0
from aglab2
with GNU General Public License v3.0
from aglab2
public void KillProcess()
{
Process.Kill();
}
19
Source : RecordServiceTasks.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void ScanWinSessionsToRecordOrEnd(object state)
{
int[] winSessions = WTSEngine.GetActiveSessions();
var rcdProcesses = GetRcordingProcesses();
// if not recording, record it.
foreach (int sid in winSessions)
{
if (Array.Find(rcdProcesses, p => p.SessionId == sid) == null)
{
string user = WTSEngine.GetDomainUserBySessionId(sid);
if (UserPolicy.IsUserRecording(user))
{
TraceLogger.Instance.WriteLineInfo("Start recording by configuration. user: " + user);
this.SessionLogon(sid);
}
}
}
// if exclude recoding, kill it.
//foreach (var proc in rcdProcesses)
//{
// string user = WTSEngine.GetDomainUserBySessionId(proc.SessionId);
// if (!IsUserRecording(user))
// {
// TraceLogger.Instance.WriteLineInfo("Stop recording by configuration. user: " + user);
// try { proc.Kill(); }
// catch (Exception) { }
// this.SessionLogoff(proc.SessionId);
// }
//}
// if session not active, remove watcher.
foreach (int sid in _watchers.Keys)
{
if (!Array.Exists(winSessions, s => s == sid))
this.SessionLogoff(sid);
}
///? bug fix: double agent process in windows 7.
List<int> sessions = new List<int>();
foreach (var proc in rcdProcesses)
{
if (sessions.Contains(proc.SessionId))
{
TraceLogger.Instance.WriteLineInfo("Kill recording agent because double process. sessionId: " + proc.SessionId);
try { proc.Kill(); }
catch (Exception) { }
}
else
{
sessions.Add(proc.SessionId);
}
}
// dispose
Array.ForEach(rcdProcesses, p => p.Dispose());
}
19
Source : RecordService.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
protected override void OnShutdown()
{
try
{
Array.ForEach(Process.GetProcessesByName("rcda"), p => p.Kill());
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
}
19
Source : Program.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static void Uninstall(string[] args)
{
try
{
// check admin preplacedword.
//string pwd = args.Length > 1 ? args[1] : null;
//if (bfbd.Common.Encryption.Encrypt(pwd) == bfbd.UltraRecord.Global.Config.AdminPreplacedword)
{
// uninstall.
new bfbd.UltraRecord.Client.ServiceInstaller().Uninstall(args);
// kill agents.
try { foreach (var p in System.Diagnostics.Process.GetProcessesByName("rcda")) p.Kill(); }
catch (Exception) { }
//try
//{
// Directory.Delete(bfbd.UltraRecord.Client.LocalStorage.DataPath, true);
// Directory.Delete(bfbd.UltraRecord.Core.CacheManager.CachePath, true);
//}
//catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
}
//else
//MessageBox.Show(null, "Incorrect preplacedword.", "Terminal Camera");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.InnerException == null ? "" : Environment.NewLine + ex.InnerException.Message);
throw;
}
}
19
Source : Util.cs
with MIT License
from ajayyy
with MIT License
from ajayyy
public static void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
// NOTE: The recommended call for exiting a Unity app is UnityEngine.Application.Quit(), but as
// of 5.1.0f3 this was causing the application to crash. The following works without crashing:
System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
}
19
Source : mainForm.cs
with MIT License
from ajohns6
with MIT License
from ajohns6
private void OnApplicationExit(object sender, EventArgs e)
{
foreach (Process process in processes)
{
process.Kill();
}
}
19
Source : mainForm.cs
with MIT License
from ajohns6
with MIT License
from ajohns6
private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (Process process in processes)
{
process.Kill();
}
}
19
Source : SteamVR_LoadLevel.cs
with MIT License
from ajayyy
with MIT License
from ajayyy
IEnumerator LoadLevel()
{
// Optionally rotate loading screen transform around the camera into view.
// We replacedume here that the loading screen is already facing toward the origin,
// and that the progress bar transform (if any) is a child and will follow along.
if (loadingScreen != null && loadingScreenDistance > 0.0f)
{
// Wait until we have tracking.
var hmd = SteamVR_Controller.Input((int)OpenVR.k_unTrackedDeviceIndex_Hmd);
while (!hmd.hasTracking)
yield return null;
var tloading = hmd.transform;
tloading.rot = Quaternion.Euler(0.0f, tloading.rot.eulerAngles.y, 0.0f);
tloading.pos += tloading.rot * new Vector3(0.0f, 0.0f, loadingScreenDistance);
var t = loadingScreenTransform != null ? loadingScreenTransform : transform;
t.position = tloading.pos;
t.rotation = tloading.rot;
}
_active = this;
SteamVR_Events.Loading.Send(true);
// Calculate rate for fading in loading screen and progress bar.
if (loadingScreenFadeInTime > 0.0f)
{
fadeRate = 1.0f / loadingScreenFadeInTime;
}
else
{
alpha = 1.0f;
}
var overlay = OpenVR.Overlay;
// Optionally create our loading screen overlay.
if (loadingScreen != null && overlay != null)
{
loadingScreenOverlayHandle = GetOverlayHandle("loadingScreen", loadingScreenTransform != null ? loadingScreenTransform : transform, loadingScreenWidthInMeters);
if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
{
var texture = new Texture_t();
texture.handle = loadingScreen.GetNativeTexturePtr();
texture.eType = SteamVR.instance.textureType;
texture.eColorSpace = EColorSpace.Auto;
overlay.SetOverlayTexture(loadingScreenOverlayHandle, ref texture);
}
}
bool fadedForeground = false;
// Fade out to compositor
SteamVR_Events.LoadingFadeOut.Send(fadeOutTime);
// Optionally set a skybox to use as a backdrop in the compositor.
var compositor = OpenVR.Compositor;
if (compositor != null)
{
if (front != null)
{
SteamVR_Skybox.SetOverride(front, back, left, right, top, bottom);
// Explicitly fade to the compositor since loading will cause us to stop rendering.
compositor.FadeGrid(fadeOutTime, true);
yield return new WaitForSeconds(fadeOutTime);
}
else if (backgroundColor != Color.clear)
{
// Otherwise, use the specified background color.
if (showGrid)
{
// Set compositor background color immediately, and start fading to it.
compositor.FadeToColor(0.0f, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, true);
compositor.FadeGrid(fadeOutTime, true);
yield return new WaitForSeconds(fadeOutTime);
}
else
{
// Fade the foreground color in (which will blend on top of the scene), and then cut to the compositor.
compositor.FadeToColor(fadeOutTime, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, false);
yield return new WaitForSeconds(fadeOutTime + 0.1f);
compositor.FadeGrid(0.0f, true);
fadedForeground = true;
}
}
}
// Now that we're fully faded out, we can stop submitting frames to the compositor.
SteamVR_Render.pauseRendering = true;
// Continue waiting for the overlays to fully fade in before continuing.
while (alpha < 1.0f)
yield return null;
// Keep us from getting destroyed when loading the new level, otherwise this coroutine will get stopped prematurely.
transform.parent = null;
DontDestroyOnLoad(gameObject);
if (!string.IsNullOrEmpty(internalProcessPath))
{
Debug.Log("Launching external application...");
var applications = OpenVR.Applications;
if (applications == null)
{
Debug.Log("Failed to get OpenVR.Applications interface!");
}
else
{
var workingDirectory = Directory.GetCurrentDirectory();
var fullPath = Path.Combine(workingDirectory, internalProcessPath);
Debug.Log("LaunchingInternalProcess");
Debug.Log("ExternalAppPath = " + internalProcessPath);
Debug.Log("FullPath = " + fullPath);
Debug.Log("ExternalAppArgs = " + internalProcessArgs);
Debug.Log("WorkingDirectory = " + workingDirectory);
var error = applications.LaunchInternalProcess(fullPath, internalProcessArgs, workingDirectory);
Debug.Log("LaunchInternalProcessError: " + error);
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#elif !UNITY_METRO
System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
}
}
else
{
var mode = loadAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single;
if (loadAsync)
{
Application.backgroundLoadingPriority = ThreadPriority.Low;
async = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(levelName, mode);
// Performing this in a while loop instead seems to help smooth things out.
//yield return async;
while (!async.isDone)
{
yield return null;
}
}
else
{
UnityEngine.SceneManagement.SceneManager.LoadScene(levelName, mode);
}
}
yield return null;
System.GC.Collect();
yield return null;
Shader.WarmupAllShaders();
// Optionally wait a short period of time after loading everything back in, but before we start rendering again
// in order to give everything a change to settle down to avoid any hitching at the start of the new level.
yield return new WaitForSeconds(postLoadSettleTime);
SteamVR_Render.pauseRendering = false;
// Fade out loading screen.
if (loadingScreenFadeOutTime > 0.0f)
{
fadeRate = -1.0f / loadingScreenFadeOutTime;
}
else
{
alpha = 0.0f;
}
// Fade out to compositor
SteamVR_Events.LoadingFadeIn.Send(fadeInTime);
// Refresh compositor reference since loading scenes might have invalidated it.
compositor = OpenVR.Compositor;
if (compositor != null)
{
// Fade out foreground color if necessary.
if (fadedForeground)
{
compositor.FadeGrid(0.0f, false);
compositor.FadeToColor(fadeInTime, 0.0f, 0.0f, 0.0f, 0.0f, false);
yield return new WaitForSeconds(fadeInTime);
}
else
{
// Fade scene back in, and reset skybox once no longer visible.
compositor.FadeGrid(fadeInTime, false);
yield return new WaitForSeconds(fadeInTime);
if (front != null)
{
SteamVR_Skybox.ClearOverride();
}
}
}
// Finally, stick around long enough for our overlays to fully fade out.
while (alpha > 0.0f)
yield return null;
if (overlay != null)
{
if (progressBarOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
overlay.HideOverlay(progressBarOverlayHandle);
if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
overlay.HideOverlay(loadingScreenOverlayHandle);
}
Destroy(gameObject);
_active = null;
SteamVR_Events.Loading.Send(false);
}
19
Source : CreateThreadTests.cs
with MIT License
from Akaion
with MIT License
from Akaion
public void Dispose()
{
_process.Kill();
_process.Dispose();
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from akshinmustafayev
with GNU Affero General Public License v3.0
from akshinmustafayev
private void TasksListStop_Click(object sender, RoutedEventArgs e)
{
try
{
Button buttonStop = sender as Button;
int processID = ((TaskListTask)buttonStop.DataContext).TaskID;
Process.GetProcessById(processID).Kill();
AddTextToEventsList("Process has been cancelled by user!", false);
RemoveTaskFromTasksList(processID, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
AddTextToEventsList("Process cancelled failed: " + ex.Message, false);
}
}
19
Source : WindowServiceTests.cs
with Apache License 2.0
from AKruimink
with Apache License 2.0
from AKruimink
public void Dispose()
{
// Note: as the _windowProcessList contains all the proccess we spawned we don't need to kill the _processList separately
foreach (var process in _windowProcessList)
{
process.Kill();
process.Dispose();
}
_windowProcessList.Clear();
_processList.Clear();
}
19
Source : ActionMods.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
public static Tuple<bool, string, bool> ExecuteModAction(string name, string parameter = "") {
MainProgram.DoDebug("[MOD ACTION] Running mod action \"" + name + "\"");
string actionErrMsg = "No error message set",
modLocation = Path.Combine(MainProgram.actionModsPath, modActions[name]),
infoJsonFile = Path.Combine(modLocation, "info.json");
if (File.Exists(infoJsonFile)) {
string modFileContent = ReadInfoFile(infoJsonFile);
if (modFileContent != null) {
try {
dynamic jsonTest = JsonConvert.DeserializeObject<dynamic>(modFileContent);
if (jsonTest != null) {
if (ValidateInfoJson(jsonTest)) {
//JSON is valid - get script file
string scriptFile = jsonTest["options"]["file_name"], scriptFileLocation = Path.Combine(modLocation, scriptFile);
bool actionIsFatal = jsonTest["options"]["is_fatal"] ?? false,
requiresParameter = jsonTest["options"]["requires_param"] ?? false,
requiresSecondaryParameter = jsonTest["options"]["require_second_param"] ?? false;
if (requiresParameter ? !String.IsNullOrEmpty(parameter) : true) {
Console.WriteLine("Requires parameter? " + requiresParameter);
Console.WriteLine("Has parameter? " + !String.IsNullOrEmpty(parameter));
string[] secondaryParameters = ActionChecker.GetSecondaryParam(parameter);
if (requiresSecondaryParameter ? secondaryParameters.Length > 1 : true) { //Also returns the first parameter
if (File.Exists(scriptFileLocation)) {
string accArg = requiresParameter && requiresSecondaryParameter ? JsonConvert.SerializeObject(ActionChecker.GetSecondaryParam(parameter)) : (requiresParameter ? parameter : "");
try {
ProcessStartInfo p = new ProcessStartInfo {
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
string theExtension = Path.GetExtension(scriptFile);
if (theExtension == ".ps1") {
//Is powershell - open it correctly
p.FileName = "powershell.exe";
p.Arguments = String.Format("-WindowStyle Hidden -file \"{0}\" \"{1}\"", scriptFileLocation, accArg);
} else if (theExtension == ".py") {
//Python - open it correctly
string minPythonVersion = (jsonTest["options"]["min_python_version"] ?? ""),
maxPythonVersion = (jsonTest["options"]["max_python_version"] ?? ""),
pythonPath = GetPythonPath(minPythonVersion, maxPythonVersion);
if (pythonPath != "") {
p.FileName = GetPythonPath();
p.Arguments = String.Format("{0} \"{1}\"", scriptFileLocation, accArg);
} else {
//No python version (or one with the min-max requirements) not found.
string pythonErr;
if (minPythonVersion == "" && maxPythonVersion == "") {
//Python just not found
pythonErr = "We could not locate Python on your computer. Please either download Python or specify its path in the ACC settings if it's already installed.";
} else {
if (minPythonVersion != "" && maxPythonVersion != "") {
//Both min & max set
pythonErr = "We could not locate a version of Python between v" + minPythonVersion + " and v" + maxPythonVersion + ". Please either download a version of Python in between the specified versions, or specify its path in the ACC settings if it's already installed.";
} else {
if (minPythonVersion != "") {
//Min only
pythonErr = "We could not locate a version of Python greater than v" + minPythonVersion + ". Please either download Python (min version " + minPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
} else {
//Max only
pythonErr = "We could not locate a version of Python lower than v" + maxPythonVersion + ". Please either download Python (max version " + maxPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
}
}
}
return Tuple.Create(false, pythonErr, false);
}
} else if (theExtension == ".bat" || theExtension == ".cmd" || theExtension == ".btm") {
//Is batch - open it correctly (https://en.wikipedia.org/wiki/Batch_file#Filename_extensions)
p.FileName = "cmd.exe";
p.Arguments = String.Format("/c {0} \"{1}\"", scriptFileLocation, accArg);
} else {
//"Other" filetype. Simply open file.
p.FileName = scriptFileLocation;
p.Arguments = accArg;
}
Process theP = Process.Start(p);
if (!theP.WaitForExit(5000)) {
MainProgram.DoDebug("Action mod timed out");
theP.Kill();
}
string output = theP.StandardOutput.ReadToEnd();
using (StringReader reader = new StringReader(output)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (line.Length >= 17) {
if (line.Substring(0, 12) == "[ACC RETURN]") {
//Return for ACC
string returnContent = line.Substring(13),
comment = returnContent.Contains(',') ? returnContent.Split(',')[1] : "";
bool actionSuccess = returnContent.Substring(0, 4) == "true";
if (comment.Length > 0 && char.IsWhiteSpace(comment, 0)) {
comment = comment.Substring(1);
}
if (actionSuccess) {
//Action was successfull
Console.WriteLine("Action successful!");
} else {
//Action was not successfull
Console.WriteLine("Action failed :(");
}
Console.WriteLine("Comment; " + comment);
return Tuple.Create(actionSuccess, (comment.Length > 0 ? comment : "Action mod returned no reason for failing"), actionIsFatal);
}
}
}
}
return Tuple.Create(false, "Action mod didn't return anything to ACC", false);
} catch (Exception e) {
//Process init failed - it shouldn't, but better safe than sorry
actionErrMsg = "Process initiation failed";
Console.WriteLine(e);
}
} else {
//Script file doesn't exist
actionErrMsg = "Action mod script doesn't exist";
}
} else {
actionErrMsg = "Action \"" + name + "\" requires a secondary parameter to be set";
}
} else {
actionErrMsg = "Action \"" + name + "\" requires a parameter to be set";
}
} else {
//JSON is not valid; validateErrMsg
actionErrMsg = validateErrMsg;
}
} else {
//JSON is invalid or failed
actionErrMsg = "Action mod JSON is invalid";
}
} catch (Exception e) {
//Failed to parse
actionErrMsg = "Failed to parse action mod JSON";
Console.WriteLine(e.Message);
}
} else {
//Couldn't read file
MainProgram.DoDebug("1");
}
} else {
MainProgram.DoDebug("0; " + modLocation);
}
return Tuple.Create(false, actionErrMsg, false);
}
19
Source : MainProgram.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[STAThread]
static void Main(string[] args) {
Console.WriteLine("Log location; " + logFilePath);
CheckSettings();
var config = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
NLog.LogManager.Configuration = config;
void ActualMain() {
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//Upgrade settings
if (Properties.Settings.Default.UpdateSettings) {
/* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
try {
Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);
foreach (string dir in directories) {
if (dir != currentFolder.ToString()) {
var directoriesInDir = Directory.GetDirectories(dir);
foreach (string childDir in directoriesInDir) {
string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
if (!Directory.Exists(checkPath)) {
string checkFile = Path.Combine(childDir, "user.config");
if (File.Exists(checkFile)) {
bool xmlHasError = false;
try {
XmlDoreplacedent xml = new XmlDoreplacedent();
xml.Load(checkFile);
xml.Validate(null);
} catch {
xmlHasError = true;
DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
}
if (!xmlHasError) {
Directory.CreateDirectory(checkPath);
File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
}
}
}
}
}
}
} catch (Exception e) {
Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
}
/* End "copy settings" */
try {
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.UpdateSettings = false;
Properties.Settings.Default.Save();
} catch {
DoDebug("Failed to upgrade from old settings file.");
}
Console.WriteLine("Upgraded settings to match last version");
}
if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
Properties.Settings.Default.LastUpdated = DateTime.Now;
}
//Create action mod path
if (!Directory.Exists(actionModsPath)) {
Directory.CreateDirectory(actionModsPath);
}
//Translator
string tempDir = Path.Combine(currentLocation, "Translations");
if (Directory.Exists(tempDir)) {
Translator.translationFolder = Path.Combine(currentLocation, "Translations");
Translator.languagesArray = Translator.GetLanguages();
} else {
MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
}
string lang = Properties.Settings.Default.ActiveLanguage;
if (Array.Exists(Translator.languagesArray, element => element == lang)) {
DoDebug("ACC running with language \"" + lang + "\"");
Translator.SetLanguage(lang);
} else {
DoDebug("Invalid language chosen (" + lang + ")");
Properties.Settings.Default.ActiveLanguage = "English";
Translator.SetLanguage("English");
}
//End translator
sysIcon = new SysTrayIcon();
Properties.Settings.Default.TimesOpened += 1;
Properties.Settings.Default.Save();
SetupDataFolder();
if (File.Exists(logFilePath)) {
try {
File.WriteAllText(logFilePath, string.Empty);
} catch {
// Don't let this being DENIED crash the software
Console.WriteLine("Failed to empty the log");
}
} else {
Console.WriteLine("Trying to create log");
CreateLogFile();
}
//Check if software already runs, if so kill this instance
var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
if (otherACCs.Length > 1) {
//Try kill the _other_ process instead
foreach (Process p in otherACCs) {
if (p.Id != Process.GetCurrentProcess().Id) {
try {
p.Kill();
DoDebug("Other ACC instance was running. Killed it.");
} catch {
DoDebug("Could not kill other process of ACC; access denied");
}
}
}
}
Application.EnableVisualStyles();
DoDebug("[ACC begun (v" + softwareVersion + ")]");
if (Properties.Settings.Default.CheckForUpdates) {
if (HasInternet()) {
new Thread(() => {
new SoftwareUpdater().Check();
}).Start();
} else {
DoDebug("Couldn't check for new update as PC does not have access to the internet");
}
}
//On console close: hide NotifyIcon
Application.ApplicationExit += new EventHandler(OnApplicationExit);
handler = new ConsoleEventDelegate(ConsoleEventCallback);
SetConsoleCtrlHandler(handler, true);
//Create shortcut folder if doesn't exist
if (!Directory.Exists(shortcutLocation)) {
Directory.CreateDirectory(shortcutLocation);
}
if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
//Create example-file
try {
using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
sw.WriteLine("This is an example file.");
sw.WriteLine("If you haven't already, make your replacedistant open this file!");
}
} catch {
DoDebug("Could not create or write to example file");
}
}
//Delete all old action files
if (Directory.Exists(CheckPath())) {
DoDebug("Deleting all files in action folder");
foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
int timeout = 0;
if (File.Exists(file)) {
while (ActionChecker.FileInUse(file) && timeout < 5) {
timeout++;
Thread.Sleep(500);
}
if (timeout >= 5) {
DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
} else {
try {
File.Delete(file);
} catch (Exception e) {
DoDebug("Failed to delete file at " + file + "; " + e.Message);
}
}
}
}
DoDebug("Old action files removed - moving on...");
}
//SetupListener();
watcher = new FileSystemWatcher() {
Path = CheckPath(),
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName,
Filter = "*." + Properties.Settings.Default.ActionFileExtension,
EnableRaisingEvents = true
};
watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
watcher.Error += delegate { DoDebug("Something wen't wrong"); };
DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");
sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
SetStartup(true);
key.CreateSubKey("replacedistantComputerControl");
key = key.OpenSubKey("replacedistantComputerControl", true);
key.SetValue("FirstTime", false);
ShowGettingStarted();
DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
} else {
if (!Properties.Settings.Default.HasCompletedTutorial) {
ShowGettingStarted();
DoDebug("Didn't finish setup guide last time, opening again");
}
}
SetRegKey("ActionFolder", CheckPath());
SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);
testActionWindow = new TestActionWindow();
//If newly updated
if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
//Up(or down)-grade, display version notes
DoDebug("ACC has been updated");
if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
//Had issues before; fixed now
DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");
try {
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rk.DeleteValue(appName, false);
} catch {
DoDebug("Failed to remove old start with win run");
}
SetStartup(true);
} else {
if (ACCStartsWithWindows()) {
SetStartup(true);
}
}
Properties.Settings.Default.LastUpdated = DateTime.Now;
if (gettingStarted != null) {
DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
aboutVersionAwaiting = true;
} else {
Properties.Settings.Default.LastKnownVersion = softwareVersion;
new NewVersion().Show();
}
Properties.Settings.Default.Save();
}
//Check if software starts with Windows
if (!ACCStartsWithWindows())
sysIcon.AddOpenOnStartupMenu();
/* 'Evalufied' user feedback implementation */
if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
&& gettingStarted == null
&& !Properties.Settings.Default.HasPromptedFeedback) {
//User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
//(also the "getting started" window is not showing)
if (HasInternet()) {
try {
WebRequest request = WebRequest.Create("https://evalufied.dk/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK) {
DoDebug("'Evalufied' is down - won't show faulty feedback window");
} else {
DoDebug("Showing 'User Feedback' window");
Properties.Settings.Default.HasPromptedFeedback = true;
Properties.Settings.Default.Save();
new UserFeedback().Show();
}
} catch {
DoDebug("Failed to check for 'Evalufied'-availability");
}
} else {
DoDebug("No internet connection, not showing user feedback window");
}
}
//Action mods implementation
ActionMods.CheckMods();
TaskSchedulerSetup();
hreplacedtarted = true;
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep
Application.Run();
}
if (sentryToken != "super_secret") {
//Tracking issues with Sentry.IO - not forked from GitHub (official version)
bool sentryOK = false;
try {
if (Properties.Settings.Default.UID != "") {
Properties.Settings.Default.UID = Guid.NewGuid().ToString();
Properties.Settings.Default.Save();
}
if (Properties.Settings.Default.UID != "") {
SentrySdk.ConfigureScope(scope => {
scope.User = new Sentry.Protocol.User {
Id = Properties.Settings.Default.UID
};
});
}
using (SentrySdk.Init(sentryToken)) {
sentryOK = true;
}
} catch {
//Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
DoDebug("Sentry initiation failed");
ActualMain();
}
if (sentryOK) {
try {
using (SentrySdk.Init(sentryToken)) {
DoDebug("Sentry initiated");
ActualMain();
}
} catch {
ActualMain();
}
}
} else {
//Code is (most likely) forked - skip issue tracking
ActualMain();
}
}
19
Source : MonitoredProcess.cs
with MIT License
from Aleksbgbg
with MIT License
from Aleksbgbg
internal void Kill()
{
Killed = true;
if (_hreplacedtarted)
{
_process.Kill();
}
else
{
OnExited();
}
}
19
Source : PowershellStarter.cs
with MIT License
from AlexAsplund
with MIT License
from AlexAsplund
protected override void OnStop()
{
// If script hasn't already exited, kill it
if (!PSProcess.HasExited) {
PSProcess.Kill();
}
eventLog1.WriteEntry("PowershellStarter Stopped.");
}
19
Source : AutoStarter.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public static void SetAutoStartByScheduler(string keyName, string replacedemblyLocation)
{
var fileName = "schtasks.exe";
var arguments = "/create /sc onlogon /tn \"{0}\" /rl highest /tr \"{1}\"";
arguments = string.Format(arguments, keyName, replacedemblyLocation);
var scheduleProcess = new Process();
scheduleProcess.StartInfo.CreateNoWindow = true;
scheduleProcess.StartInfo.UseShellExecute = false;
scheduleProcess.StartInfo.FileName = fileName;
scheduleProcess.StartInfo.Arguments = arguments;
scheduleProcess.Start();
if (!scheduleProcess.WaitForExit(30000))
{
scheduleProcess.Kill();
}
}
19
Source : AutoStarter.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public static void UnsetAutoStartByScheduler(string keyName)
{
var fileName = "schtasks.exe";
var arguments = "/delete /tn \"{0}\" /f";
arguments = string.Format(arguments, keyName);
var scheduleProcess = new Process();
scheduleProcess.StartInfo.CreateNoWindow = true;
scheduleProcess.StartInfo.UseShellExecute = false;
scheduleProcess.StartInfo.FileName = fileName;
scheduleProcess.StartInfo.Arguments = arguments;
scheduleProcess.Start();
if (!scheduleProcess.WaitForExit(30000))
{
scheduleProcess.Kill();
}
}
19
Source : PuppeteerEngine.cs
with MIT License
from AlexCSDev
with MIT License
from AlexCSDev
private void KillChromeIfRunning()
{
Process[] processList = Process.GetProcessesByName("chrome");
if (processList.Length > 0)
{
_logger.Debug($"Found {processList.Length} chrome processes (not sure which one yet)");
processList = processList.Where(x =>
x.MainModule != null && x.MainModule.FileName.Contains(AppDomain.CurrentDomain.BaseDirectory))
.ToArray();
if (processList.Length > 0)
{
_logger.Debug($"{processList.Length} chrome processes are in patreondownloader's folder");
_logger.Warn("Running PatreonDownloader's Chrome detected. Attempting to close it...");
bool failed = false;
foreach (Process process in processList)
{
_logger.Debug($"Attempting to kill PID {process.Id}");
try
{
process.Kill();
}
catch (Exception ex)
{
failed = true;
_logger.Error($"Error while closing chrome: {ex}");
}
}
if (failed)
{
_logger.Error(
"Unable to close some or all PatreonDownloader's Chrome instances. Please close them manually via process manager if you encounter any problems running this application.");
}
else
{
_logger.Info("Successfully killed all PatreonDownloader's Chrome instances.");
}
}
}
}
19
Source : WpfRestoreService.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public void HardApplicationRestart()
{
Process.Start(Application.Resourcereplacedembly.Location);
Process.GetCurrentProcess().Kill();
}
19
Source : UpdateAssist.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private async Task<(int exitCode, string output)> InvokeProcessAsync(ProcessStartInfo psi, CancellationToken ct)
{
var pi = Process.Start(psi);
await Task.Run(() =>
{
while (!ct.IsCancellationRequested)
{
if (pi.WaitForExit(2000))
{
return;
}
}
if (ct.IsCancellationRequested)
{
pi.Kill();
ct.ThrowIfCancellationRequested();
}
});
string textResult = await pi.StandardOutput.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(textResult) || pi.ExitCode != 0)
{
textResult = (textResult ?? string.Empty) + "\n" + await pi.StandardError.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(textResult))
{
textResult = string.Empty;
}
}
return (pi.ExitCode, textResult.Trim());
}
19
Source : CrashHandler.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
string crashDir = Path.Combine(Program.AppDataDirectory, "crash");
Directory.CreateDirectory(crashDir);
CreateBackups(crashDir);
Exception ex = (Exception) e.ExceptionObject;
CreateCrashLog(crashDir, ex);
MessageBox.Show(
Strings.ProgramTerminates, Strings.CriticalError,
MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Diagnostics.Process.Start(crashDir);
System.Diagnostics.Process.GetCurrentProcess().Kill();
// Goodbye!
}
}
19
Source : ProjectInstaller.cs
with MIT License
from alexis-
with MIT License
from alexis-
private void StopAgent()
{
var runningAgents = Process.GetProcessesByName("BitShelter.Agent"); // There should be only one
foreach (var p in runningAgents)
{
try
{
p.Kill();
}
catch (Exception)
{
}
}
}
19
Source : MainWindow.xaml.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void ButtonTesterCandleOne_Click(object sender, RoutedEventArgs e)
{
try
{
Hide();
TesterUi candleOneUi = new TesterUi();
candleOneUi.ShowDialog();
Close();
ProccesIsWorked = false;
Thread.Sleep(5000);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
Process.GetCurrentProcess().Kill();
}
See More Examples