C# – Show or Hide Process

email me

This is how you create a form with two buttons that will either Show a process, or Hide a process.

Tested in Visual Studio 2017.

Form1.cs

using System;
using System.Diagnostics; // Process
using System.Runtime.InteropServices; // DllImport
using System.Windows.Forms; // Windows Form

namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
int hWnd = 0;

private const int SW_HIDE = 0;
private const int SW_SHOW = 5;
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow);
private void button1_Click(object sender, EventArgs e)
{

MessageBox.Show("Hide Process");

Process[] processRunning = Process.GetProcesses();
foreach (Process pr in processRunning)
{
if (pr.ProcessName == "notepad")
{
hWnd = pr.MainWindowHandle.ToInt32();
ShowWindow(hWnd, SW_HIDE);
}
}

}

private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Show Process");

if (hWnd != 0)
{
ShowWindow(hWnd, SW_SHOW);
hWnd = 0;
}

}

public Form1()
{
InitializeComponent();
}

}

}

 

Form1.Designer.cs

namespace WindowsFormsApp8
{
partial class Form1
{
///

<summary>
/// Required designer variable.
/// </summary>private System.ComponentModel.IContainer components = null;

///

<summary>
/// Clean up any resources being used.
/// </summary>/// <param name="disposing">true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if (disposing (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

///

<summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>private void InitializeComponent()
{
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button2
//
this.button2.Location = new System.Drawing.Point(48, 35);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "Show";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(48, 89);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Hide";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(169, 162);
this.Controls.Add(this.button1);
this.Controls.Add(this.button2);
this.Name = "Form1";
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;

}
}