Skip to content

Instantly share code, notes, and snippets.

@decay88
Created March 9, 2020 14:54
Show Gist options
  • Save decay88/761a3f081269b96191bb77d4813f23d3 to your computer and use it in GitHub Desktop.
Save decay88/761a3f081269b96191bb77d4813f23d3 to your computer and use it in GitHub Desktop.
C# Useful References
Environment.Is64BitOperatingSystem;
Environment.Is64BitProcess;
// or
if (IntPtr.Size == 8)
{
// 64 bit machine
}
else if (IntPtr.Size == 4)
{
// 32 bit machine
}
// or
bool is64Bit = System.Environment.Is64BitOperatingSystem;
if (is64Bit)
{
}
else
{
}
using System.Security.Principal;
public static bool IsAdministrator
{
get
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
// Current Application
static bool IsElevated
{
get
{
return WindowsIdentity.GetCurrent().Owner
.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);
}
}
// Another Application
public class ProcessHelper
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
private const int TOKEN_ASSIGN_PRIMARY = 0x1;
private const int TOKEN_DUPLICATE = 0x2;
private const int TOKEN_IMPERSONATE = 0x4;
private const int TOKEN_QUERY = 0x8;
private const int TOKEN_QUERY_SOURCE = 0x10;
private const int TOKEN_ADJUST_GROUPS = 0x40;
private const int TOKEN_ADJUST_PRIVILEGES = 0x20;
private const int TOKEN_ADJUST_SESSIONID = 0x100;
private const int TOKEN_ADJUST_DEFAULT = 0x80;
private const int TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_SESSIONID | TOKEN_ADJUST_DEFAULT);
public static bool IsProcessOwnerAdmin(string processName)
{
Process proc = Process.GetProcessesByName(processName)[0];
IntPtr ph = IntPtr.Zero;
OpenProcessToken(proc.Handle, TOKEN_ALL_ACCESS, out ph);
WindowsIdentity iden = new WindowsIdentity(ph);
bool result = false;
foreach (IdentityReference role in iden.Groups)
{
if (role.IsValidTargetType(typeof(SecurityIdentifier)))
{
SecurityIdentifier sid = role as SecurityIdentifier;
if (sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
{
result = true;
break;
}
}
}
CloseHandle(ph);
return result;
}
}
AppDomain.CurrentDomain.BaseDirectory // Directory
using System.Reflection;
Assembly.GetEntryAssembly().Location // Exe File
Assembly.GetExecutingAssembly().GetName().Name // Program Name
Assembly.GetEntryAssembly().GetName().Version;
// GUID
var assembly = typeof(Program).Assembly;
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
var id = attribute.Value;
// or (not sure how accurate this is anymore)
static Assembly assembly = Assembly.GetExecutingAssembly();
static Mutex mutex = new Mutex(true, assembly.GetType().GUID.ToString());
public static string AssemblyDirectory {
get {
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
public static async Task Method1()
{
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
}
});
}
// File Attributes [C#]
string filePath = @"c:\test.txt";
// get file attributes
FileAttributes fileAttributes = File.GetAttributes(filePath);
Set file attributes
To set file attributes use static method File.SetAttri­butes. Parameter of the method is a bitwise combination of FileAttributes enumeration.
// clear all file attributes
File.SetAttributes(filePath, FileAttributes.Normal);
// set just only archive and read only attributes (no other attribute will set)
File.SetAttributes(filePath, FileAttributes.Archive |
FileAttributes.ReadOnly);
// check whether a file is read only
bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
// check whether a file is hidden
bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden);
// check whether a file has archive attribute
bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive);
// check whether a file is system file
bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System);
// set (add) hidden attribute (hide a file)
File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden);
// set (add) both archive and read only attributes
File.SetAttributes(filePath, File.GetAttributes(filePath) | (FileAttributes.Archive |
FileAttributes.ReadOnly));
Delete/clear file attributes from current ones
To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator with a mask (bitwise complement of desired attributes combination).
// delete/clear hidden attribute
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.Hidden);
// delete/clear archive and read only attributes
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~(FileAttributes.Archive |
FileAttributes.ReadOnly));
AutoClosingMessageBox.Show("Message", "Caption", 2000);
public class AutoClosingMessageBox
{
System.Threading.Timer _timeoutTimer;
string _caption;
AutoClosingMessageBox(string text, string caption, int timeout)
{
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
using (_timeoutTimer)
MessageBox.Show(text, caption);
}
public static void Show(string text, string caption, int timeout)
{
new AutoClosingMessageBox(text, caption, timeout);
}
void OnTimerElapsed(object state)
{
IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
if (mbWnd != IntPtr.Zero)
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
}
const int WM_CLOSE = 0x0010;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
private delegate void WorkerDelegate();
private void ActualWork()
{
// Do the background work here
}
public void ActualWorkAsync()
{
WorkerDelegate worker = new WorkerDelegate(ActualWork);
AsyncCallback completedCallback = new AsyncCallback(Callback);
AsyncOperation async = AsyncOperationManager.CreateOperation(null);
worker.BeginInvoke(completedCallback, async);
}
private void Callback(IAsyncResult ar)
{
WorkerDelegate worker = (WorkerDelegate)((AsyncResult)ar).AsyncDelegate;
AsyncOperation async = (AsyncOperation)ar.AsyncState;
worker.EndInvoke(ar);
AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null, false, null);
async.PostOperationCompleted(delegate(object e) { onWorkCompleted((AsyncCompletedEventArgs)e); },completedArgs);
}
protected void onWorkCompleted(AsyncCompletedEventArgs e)
{
}
// or simplified version
BackgroundWorker worker;
private void Worker()
{
worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
// Do the background work here
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
worker.DoWork -= DoWork;
worker.RunWorkerCompleted -= Worker_RunWorkerCompleted;
}
// Put in your main
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
BlurBehind.EnableBlur(mainWindow);
}
// BlurBehind.cs
[DllImport("user32.dll")]
internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
[StructLayout(LayoutKind.Sequential)]
internal struct WindowCompositionAttributeData
{
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
internal enum WindowCompositionAttribute
{
// ...
WCA_ACCENT_POLICY = 19
// ...
}
internal enum AccentState
{
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
}
[StructLayout(LayoutKind.Sequential)]
internal struct AccentPolicy
{
public AccentState AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
internal void EnableBlur()
{
var windowHelper = new WindowInteropHelper(this);
var accent = new AccentPolicy();
var accentStructSize = Marshal.SizeOf(accent);
accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData();
data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
data.SizeOfData = accentStructSize;
data.Data = accentPtr;
SetWindowCompositionAttribute(windowHelper.Handle, ref data);
Marshal.FreeHGlobal(accentPtr);
}
AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
EasyLogger.Error("Application.ThreadException: Base Exception: " + e.Exception.GetBaseException() + Environment.NewLine + "Exception Message: " + e.Exception.Message);
}
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
EasyLogger.Error("AppDomain.UnhandledException: Exception Object: " + e.ExceptionObject + Environment.NewLine + "Exception Object: " + ((Exception)e.ExceptionObject).Message);
}
// OR
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
if (null == ex) return;
// Log this error. Logging the exception doesn't correct the problem but at least now
// you may have more insight as to why the exception is being thrown.
Debug.WriteLine("Unhandled Exception: " + ex.Message);
Debug.WriteLine("Unhandled Exception: " + ex);
MessageBox.Show(ex.Message);
}
if (int.TryParse(SomeNumber, out int value))
{
}
Process[] pname = Process.GetProcessesByName("APPNAME");
if (pname.Length == 0)
{
Thread.Sleep(500);
}
else
{
}
// OR
class MyProcess
{
void BindToRunningProcesses()
{
// Get the current process.
Process currentProcess = Process.GetCurrentProcess();
// Get all processes running on the local computer.
Process[] localAll = Process.GetProcesses();
// Get all instances of Notepad running on the local computer.
// This will return an empty array if notepad isn't running.
Process[] localByName = Process.GetProcessesByName("notepad");
// Get a process on the local computer, using the process id.
// This will throw an exception if there is no such process.
Process localById = Process.GetProcessById(1234);
// Get processes running on a remote computer. Note that this
// and all the following calls will timeout and throw an exception
// if "myComputer" and 169.0.0.0 do not exist on your local network.
// Get all processes on a remote computer.
Process[] remoteAll = Process.GetProcesses("myComputer");
// Get all instances of Notepad running on the specific computer, using machine name.
Process[] remoteByName = Process.GetProcessesByName("notepad", "myComputer");
// Get all instances of Notepad running on the specific computer, using IP address.
Process[] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");
// Get a process on a remote computer, using the process id and machine name.
Process remoteById = Process.GetProcessById(2345, "myComputer");
}
static void Main()
{
MyProcess myProcess = new MyProcess();
myProcess.BindToRunningProcesses();
}
}
using System.Windows.Forms;
[STAThread]
private static void Main(string[] arg)
{
Thread thread = new Thread(() => Clipboard.SetText("Test!"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join(); //Wait for the thread to end
}
// Pinvoke Quit
internal const uint WM_QUIT = 0x12;
[DllImport("user32.dll", EntryPoint = "PostThreadMessage", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PostThreadMessage(int idThread, uint Msg, IntPtr wParam, IntPtr lParam);
foreach (Process process in Process.GetProcessesByName("APPNAME"))
{
if (process.Id != Process.GetCurrentProcess().Id)
{
try
{
foreach (ProcessThread thread in process.Threads)
{
PostThreadMessage(thread.Id, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
}
}
catch (Exception ex)
{
ErrorHandler(ex);
}
}
}
// or pinvoke closing
internal const int WM_CLOSE = 0x0010;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
NativeMethods.SendMessage(hWindow, NativeMethods.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
// or Process
Process[] processes = Process.GetProcessesByName("APPNAME");
foreach (Process process in processes)
{
if (process.Id != Process.GetCurrentProcess().Id)
{
process.CloseMainWindow();
}
}
string args = "args";
string program = "/C sc start" + " " + args;
using (Process proc = new Process())
{
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.Arguments = program;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.Verb = "runas"; // run as admin
proc.Start();
proc.WaitForExit();
}
// WPF Recolor in code behind
button1.Background = Brushes.Gray;
// Windows Accent
// Reference PresentationCore and PresentationFramework
static System.Windows.Media.Color color = System.Windows.SystemParameters.WindowGlassColor;
System.Windows.SystemParameters.StaticPropertyChanged += WindowGlassBrush_Changed;
window.BorderBrush = System.Windows.SystemParameters.WindowGlassBrush;
// ColorShade
namespace APPNAME
{
public static class ColorHelper
{
private static System.Drawing.Color TempColor;
public static System.Windows.Media.SolidColorBrush ColorShade(System.Windows.Media.Color color, bool SetLightColor)
{
if (SetLightColor)
{
TempColor = System.Windows.Forms.ControlPaint.Light(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B));
}
else
{
TempColor = System.Windows.Forms.ControlPaint.Dark(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B));
}
return new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(TempColor.A, TempColor.R, TempColor.G, TempColor.B));
}
}
}
// Main
public class MyColorTable : ProfessionalColorTable
{
public override Color MenuItemBorder
{
get { return Color.FromArgb(0); }
}
public override Color MenuItemSelected
{
get { return Color.FromArgb(0, 82, 164); }
}
public override Color ToolStripDropDownBackground
{
get { return Color.FromArgb(22, 22, 22); }
}
public override Color ImageMarginGradientBegin
{
get { return Color.FromArgb(22, 22, 22); }
}
public override Color ImageMarginGradientMiddle
{
get { return Color.FromArgb(22, 22, 22); }
}
public override Color ImageMarginGradientEnd
{
get { return Color.FromArgb(22, 22, 22); }
}
}
public class MyRenderer : ToolStripProfessionalRenderer
{
public MyRenderer()
: base(new MyColorTable())
{
}
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
var r = new Rectangle(e.ArrowRectangle.Location, e.ArrowRectangle.Size);
r.Inflate(-2, -6);
Pen pen = new Pen(Color.FromArgb(255, 230, 230, 230));
e.Graphics.DrawLines(pen, new Point[]{
new Point(r.Left, r.Top),
new Point(r.Right, r.Top + r.Height /2),
new Point(r.Left, r.Top+ r.Height)});
}
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
var r = new Rectangle(e.ImageRectangle.Location, e.ImageRectangle.Size);
r.Inflate(-4, -6);
Pen pen = new Pen(Color.FromArgb(255, 230, 230, 230));
e.Graphics.DrawLines(pen, new Point[]{
new Point(r.Left, r.Bottom - r.Height /2),
new Point(r.Left + r.Width /3, r.Bottom),
new Point(r.Right, r.Top)});
}
}
// Make sure to subscribe to this event
private void Form_Load(object sender, EventArgs e)
{
this._shortcutsMenuItem.ForeColor = Color.FromArgb(230, 230, 230);
this.contextMenuStrip1.ForeColor = Color.FromArgb(230, 230, 230);
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode;
this.contextMenuStrip1.ShowCheckMargin = false;
this.contextMenuStrip1.ShowImageMargin = true;
this.contextMenuStrip1.Size = new Size(242, 204);
this.contextMenuStrip1.Renderer = new MyRenderer();
if (ShortcutsFolder != null)
{
foreach (var _shortcut in ShortcutsFolder)
{
_shortcutItem = new ToolStripMenuItem();
_shortcutItem.ForeColor = Color.White;
_shortcutItem.Name = Path.GetFileNameWithoutExtension(_shortcut);
_shortcutItem.Text = Path.GetFileNameWithoutExtension(_shortcut);
try
{
if (File.Exists(_shortcut))
{
IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
IWshRuntimeLibrary.IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(_shortcut);
_shortcutItem.Image = Icon.ExtractAssociatedIcon(link.TargetPath).ToBitmap();
}
}
catch (Exception)
{
// ignore
}
_shortcutItem.Click += Open_shortcut_Click;
_shortcutsMenuItem.DropDownItems.Add(_shortcutItem);
}
this.contextMenuStrip1.Items.Add(_shortcutsMenuItem);
this.contextMenuStrip1.Items.Add(toolStripSeparator1);
}
this.contextMenuStrip1.Items.AddRange(new ToolStripItem[] {
this.ExitMenuItem});
contextMenuStrip1.Opacity = 0.8;
_shortcutsMenuItem.DropDown.Opacity = 0.8;
}
// Designer.cs
using AppName.Properties;
namespace AppName
{
partial class AppNameForm
{
/// <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.</param>
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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AppNameForm));
notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.ExitMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this._shortcutsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// notifyIcon1
//
notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
//
// ExitMenuItem
//
this.ExitMenuItem.Name = "ExitMenuItem";
this.ExitMenuItem.Size = new System.Drawing.Size(241, 22);
this.ExitMenuItem.Text = "Exit";
this.ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator";
this.toolStripSeparator1.Size = new System.Drawing.Size(238, 6);
//
// _shortcutsMenuItem
//
this._shortcutsMenuItem.Name = "_shortcutsMenuItem";
this._shortcutsMenuItem.Size = new System.Drawing.Size(241, 22);
this._shortcutsMenuItem.Text = "Shortcuts";
}
#endregion
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem ExitMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem _shortcutsMenuItem;
static internal System.Windows.Forms.NotifyIcon notifyIcon1;
}
}
using IWshRuntimeLibrary; // Select the "COM" tab, find and select the "Windows Script Host Object Model"
private void CreateShortcut()
{
try
{
WshShell lib = new WshShell();
IWshShortcut _startupShortcut;
string _programs = Environment.GetFolderPath(Environment.SpecialFolder.Programs);
_startupShortcut = (IWshShortcut)lib.CreateShortcut(_programs + "\\" + Assembly.GetExecutingAssembly().GetName().Name + "\\" + Assembly.GetExecutingAssembly().GetName().Name + ".lnk");
_startupShortcut.TargetPath = Assembly.GetEntryAssembly().Location;
_startupShortcut.WorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
_startupShortcut.Description = Assembly.GetExecutingAssembly().GetName().Name;
_startupShortcut.Save();
}
catch (Exception ex)
{
EasyLogger.Error(ex);
}
}
static string CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// Has \\ at the end so no need to put "\\file"
AppDomain.CurrentDomain.BaseDirectory
Creating custom eventsSection
Events can be created with the Event constructor as follows:
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
The above code example uses the EventTarget.dispatchEvent() method.
This constructor is supported in most modern browsers (with Internet Explorer being the exception). For a more verbose approach (which works with Internet Explorer), see the old-fashioned way below.
Adding custom data – CustomEvent()Section
To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data.
For example, the event could be created as follows:
var event = new CustomEvent('build', { detail: elem.dataset.time });
This will then allow you to access the additional data in the event listener:
function eventHandler(e) {
console.log('The time is: ' + e.detail);
}
The old-fashioned waySection
The older approach to creating events uses APIs inspired by Java. The following shows an example:
// Create the event.
var event = document.createEvent('Event');
// Define that the event name is 'build'.
event.initEvent('build', true, true);
// Listen for the event.
elem.addEventListener('build', function (e) {
// e.target matches elem
}, false);
// target can be any Element or other EventTarget.
elem.dispatchEvent(event);
Event bubblingSection
It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data:
<form>
<textarea></textarea>
</form>
const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
// Create a new event, allow bubbling, and provide any data you want to pass to the "details" property
const eventAwesome = new CustomEvent('awesome', {
bubbles: true,
detail: { text: () => textarea.value }
});
// The form element listens for the custom "awesome" event and then consoles the output of the passed text() method
form.addEventListener('awesome', e => console.log(e.detail.text()));
// As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point
textarea.addEventListener('input', e => e.target.dispatchEvent(eventAwesome));
Creating and dispatching events dynamicallySection
Elements can listen for events that haven't been created yet:
<form>
<textarea></textarea>
</form>
const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
form.addEventListener('awesome', e => console.log(e.detail.text()));
textarea.addEventListener('input', function() {
// Create and dispatch/trigger an event on the fly
// Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element
this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } }))
});
Triggering built-in eventsSection
This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action.
function simulateClick() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var cb = document.getElementById('checkbox');
var cancelled = !cb.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
// Get value of cell from row selected
int rowindex = dataGridView1.CurrentCell.RowIndex;
int columnindex = dataGridView1.CurrentCell.ColumnIndex;
dataGridView1.Rows[rowindex].Cells[columnindex].Value.ToString();
public partial class MainWindow : Window, IDisposable
{
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
timer.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
do
{
if (!proc.HasExited)
{
proc.Refresh();
if (proc.HasExited)
{
goto Finish;
}
if (proc.Responding)
{
Console.WriteLine("Process is responding...");
}
else
{
Console.WriteLine("Process is not responding...");
}
}
}
while (!proc.WaitForExit(500));
if (proc.HasExited)
{
goto Finish;
}
Finish:;
window.MouseDown += Window_MouseDown;
private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
e.Handled = true;
if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
{
DragMove();
}
}
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
public class Program
{
public static void Main()
{
// declaring key
var key = "b14ca5898a4e4133bbce2ea2315a1916";
// encrypt parameters
var input = string.Concat("https://myDomain.in/", "Encrypt.aspx?query=", EncryptString(key, string.Format("emailID={0}", "[email protected]")));
Console.WriteLine("Encrypted Input: " + input);
// decrypt parameters
var decrptedInput = DecryptString(key, input.Substring(input.IndexOf("=") + 1));
Console.WriteLine("Decrypted Input: " + decrptedInput);
}
public static string EncryptString(string key, string plainInput)
{
byte[] iv = new byte[16];
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
{
streamWriter.Write(plainInput);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);
}
public static string DecryptString(string key, string cipherText)
{
byte[] iv = new byte[16];
byte[] buffer = Convert.FromBase64String(cipherText);
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(buffer))
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
}
AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
EasyLogger.Error(e.Exception.Message + " Application.ThreadException");
}
static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
EasyLogger.Error(((Exception)e.ExceptionObject).Message + " AppDomain.UnhandledException");
}
FileSystemWatcher watcher;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public MainWindow()
{
InitializeComponent();
if (Args.Length > 1)
{
CurrentImage = Args[1];
ImageFolderWatcher();
OpenImage(CurrentImage);
}
}
private void ImageFolderWatcher()
{
watcher = new FileSystemWatcher();
watcher.Path = CurrentImage;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
// Do something
}
private void OnRenamed(object source, RenamedEventArgs e)
{
// Do something
}
for (int i = 0; i < (int)count; i++)
{
}
for (int i = 10 - 1; i >= 0; i--)
{
Console.WriteLine(i);
}
for (int i = 0; i < Titles.Count; i++)
{
Console.WriteLine((i + 1) + " | " + SomeTitles[i]);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (variable != null)
{
variable.Dispose();
}
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
this.Visible = false;
}
class ClientListConnection
{
private string connection; // field
public string Connection // property
{
get { return connection; }
set { connection = value; }
}
}
class Program
{
static void Main(string[] args)
{
ClientListConnection myObj = new ClientListConnection();
myObj.Connection = "Your Connection String";
}
}
// or
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
public static SecurityIdentifier SIDState
{
get
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
return identity.User;
}
}
static bool SID(string user)
{
if (SIDState != null)
{
return true;
}
else
{
return false;
}
}
public static int GetIdleTime()
{
return (Environment.TickCount & Int32.MaxValue)- (int)GetLastInputTime();
}
/// <summary>
/// Get the last input time from the input devices.
/// Exception:
/// If it cannot get the last input information then it throws an exception with
/// the appropriate message.
/// </summary>
/// <returns>Last input time in milliseconds.</returns>
public static uint GetLastInputTime()
{
LastInputInfo lastInPut = new LastInputInfo();
lastInPut.BlockSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
if (!GetLastInputInfo(ref lastInPut))
{
throw new Exception(GetLastError().ToString());
}
return lastInPut.Time;
}
//Begin dynamic library
[DllImport("xinput1_3.dll", EntryPoint = "#100", CharSet = CharSet.Unicode)]
static extern int gamepadGuide(int playerIndex, out XINPUT_Guide struc);
public struct XINPUT_Guide
{
public UInt32 eventCount;
public ushort wButtons;
public Byte bLeftTrigger;
public Byte bRightTrigger;
public short sThumbLX;
public short sThumbLY;
public short sThumbRX;
public short sThumbRY;
}
public static int guide(int playerIndex, out XINPUT_Guide struc)
{
return gamepadGuide(playerIndex, out struc);
}
public class Variables
{
//Guide Button
public static NativeMethods.CriticalHandle.XINPUT_Guide xgs;
}
public static bool GuideButton = false;
//End of dynamic library
//Begin Main Program XBox Guide Button
static void GuideButtonPress()
{
while (true)
{
Thread.Sleep(500);
if (!NativeMethods.CriticalHandle.ScreenDetection.AreApplicationFullScreen() && !Variables.WindowedGame && !Variables.GUIShowing)
{
int stat;
bool value;
for (int i = 0; i < 4; i++)
{
stat = NativeMethods.CriticalHandle.guide(0, out Variables.xgs);
if (stat != 0)
{
continue;
}
value = ((Variables.xgs.wButtons & 0x0400) != 0);
if (value && !Variables.GUIShowing)
{
try
{
Thread.Sleep(1000);
int stat2;
bool value2;
for (int i2 = 0; i2 < 4; i2++)
{
stat2 = NativeMethods.CriticalHandle.guide(0, out Variables.xgs);
if (stat2 != 0)
{
continue;
}
value2 = ((Variables.xgs.wButtons & 0x0400) != 0);
if (value2 && !Variables.GUIShowing)
{
if (Variables.GamePadConnected && !Variables.GuideButton)
{
Variables.GuideButton = true;
GamePad.SetVibration(PlayerIndex.One, 0.2f, 0.2f);
Thread.Sleep(300);
GamePad.SetVibration(PlayerIndex.One, 0f, 0f);
}
Stream stream = null;
try
{
stream = new FileStream(Variables.SysFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader SysFile = new StreamReader(stream))
{
stream = null;
if (SysFile.ReadToEnd().Contains("Fan=true"))
{
try
{
using (Process proc = new Process())
{
proc.StartInfo.FileName = Environment.CurrentDirectory + @"\FanControl\FanOn.exe";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
}
Variables.Fan = true;
}
catch (Exception ex)
{
Trace.WriteLine(DateTime.Now + Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n" + " " + ex.Message);
MessageBox.Show(Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n\n" + ex.Message, Properties.Resources.ResourceManager.GetString("FailedOperationTitle"), MessageBoxButton.OK, MessageBoxImage.Stop);
}
}
}
}
finally
{
if (stream != null)
stream.Dispose();
}
}
Thread.Sleep(3000);
}
}
catch (Exception ex)
{
Trace.WriteLine(DateTime.Now + Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n" + " " + ex.Message);
MessageBox.Show(Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n\n" + ex.Message, Properties.Resources.ResourceManager.GetString("FailedOperationTitle"), MessageBoxButton.OK, MessageBoxImage.Stop);
}
}
}
}
}
}
//End Main
foreach (Process process in Process.GetProcessesByName("notepad"))
{
if (process.Id != Process.GetCurrentProcess().Id) //Excludes the process the code is being run from
{
foreach (ProcessThread thread in process.Threads)
{
int HwND = process.MainWindowHandle.ToInt32();
// use the handle however you need
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Thread thread = new Thread(bLend);
thread.Start();
}
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private void bLend()
{
Thread.Sleep(2000);
Process.Start(@"App\bLend.exe");
Thread.Sleep(50);
IntPtr hWnd = FindWindow(null, "bLend Preferences..");
if (hWnd != IntPtr.Zero) ShowWindow(hWnd, 0);
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
BeginInvoke(new MethodInvoker(DisplayData));
// FORM
this.Invoke(new Action(() => {
Show();
}));
// WPF
Application.Current.Dispatcher.Invoke(delegate
{
Show();
});
// or
Dispatcher.Invoke(() => SendToast(false));
//Main
using static Logger.Logging;
Log();
Info("Application started.", "NetworkPing");
Warning("Application about to exit!", "MyApp");
Error(ex, "MyApp");
//Logger.cs
using System;
using System.Diagnostics;
using System.IO;
class Logging
{
static readonly string LogDirectory = Path.GetTempPath() + "\\" + AppDomain.CurrentDomain.FriendlyName;
internal static string LogFile = LogDirectory + @"\Application.log";
static readonly string LogBak = LogDirectory + @"\Application.log.bak";
public static void Log()
{
if (!Directory.Exists(LogDirectory))
{
Directory.CreateDirectory(LogDirectory);
}
if (File.Exists(LogBak))
{
File.Delete(LogBak);
}
if (File.Exists(LogFile))
{
File.Copy(LogFile, LogBak);
File.Delete(LogFile);
}
Trace.Listeners.Clear();
TextWriterTraceListener twtl = null;
try
{
twtl = new TextWriterTraceListener(LogFile);
ConsoleTraceListener ctl = null;
try
{
ctl = new ConsoleTraceListener(false);
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
}
finally
{
if (ctl != null)
{
ctl.Dispose();
}
}
}
finally
{
if (twtl != null)
{
twtl.Dispose();
}
}
}
public static void Error(string message, string module)
{
WriteEntry(message, "error", module);
}
public static void Error(Exception ex, string module)
{
WriteEntry(ex.Message, "error", module);
}
public static void Warning(string message, string module)
{
WriteEntry(message, "warning", module);
}
public static void Info(string message, string module)
{
WriteEntry(message, "info", module);
}
private static void WriteEntry(string message, string type, string module)
{
Trace.WriteLine(
string.Format("{0} ( {1} - {2} ) | {3}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
type,
module,
message));
}
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, [MarshalAs(UnmanagedType.Bool)] bool fCreate);
private DialogResult MessageForm(string text, string title, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button2)
{
using (Form form = new Form())
{
form.Opacity = 0;
form.Show();
form.WindowState = FormWindowState.Minimized;
form.WindowState = FormWindowState.Normal;
DialogResult dialogResult = MessageBox.Show(form, text, title, buttons, icon, defaultButton);
if (dialogResult == DialogResult.Yes)
{
form.Close();
}
return dialogResult;
}
}
using System;
using System.Windows.Forms;
namespace NotifyTest
{
static class Program
{
static NotifyIcon notifyIcon;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
notifyIcon = new NotifyIcon
{
Visible = true,
Icon = System.Drawing.SystemIcons.Information,
BalloonTipTitle = "Testing",
BalloonTipText = "This is only a test... " + Environment.NewLine + Environment.NewLine + "This message will close in 5 seconds."
};
notifyIcon.BalloonTipClicked += NotifyIcon_BalloonTipClicked;
notifyIcon.MouseClick += NotifyIcon_MouseClick;
notifyIcon.ShowBalloonTip(5000);
notifyIcon.BalloonTipClosed += NotifyIcon_BalloonTipClosed;
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItemClose = new MenuItem("&Close Tray");
menuItemClose.Click += MenuItemClose_Click;
contextMenu.MenuItems.Add(menuItemClose);
notifyIcon.ContextMenu = contextMenu;
Application.Run();
}
private static void NotifyIcon_BalloonTipClosed(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
}
private static void NotifyIcon_Click(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
}
private void NotifyIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
notifyIcon.Visible = false;
Application.Exit();
}
else
{
// Show();
}
}
private static void NotifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
}
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// put code here
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// put code here
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
Dispose();
}
static PerformanceCounter cpuCounter;
static PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
public string getCurrentCpuUsage(){
return cpuCounter.NextValue()+"%";
}
public string getAvailableRAM(){
return ramCounter.NextValue()+"MB";
}
public static bool PingHost(string nameOrAddress)
{
bool pingable = false;
Ping pinger = null;
try
{
pinger = new Ping();
PingReply reply = pinger.Send(nameOrAddress);
pingable = reply.Status == IPStatus.Success;
}
catch (PingException)
{
return false;
}
finally
{
if (pinger != null)
{
pinger.Dispose();
}
}
return pingable;
}
// Get HResult
try
{
SetWindowLong(explorer.HWND, GWL_EXSTYLE,
GetWindowLong(explorer.HWND, GWL_EXSTYLE) | WS_EX_LAYERED).GetTypeCode();
SetLayeredWindowAttributes(explorer.HWND, LWA_COLORKEY, 255, LWA_ALPHA);
}
catch (Win32Exception)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
// Notice the .GetTypeCode(); after the request
// Activate a window from anywhere by attaching to the foreground window
using System.Windows.Interop;
using System.Runtime.InteropServices;
namespace System.Windows
{
public static class SystemWindows
{
#region Constants
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 SWP_SHOWWINDOW = 0x0040;
#endregion
/// <summary>
/// Activate a window from anywhere by attaching to the foreground window
/// </summary>
public static void GlobalActivate(this Window window)
{
var interopHelper = new WindowInteropHelper(PassThroughNonNull(window));
var thisWindowThreadId = NativeMethods.GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);
var currentForegroundWindow = NativeMethods.GetForegroundWindow();
var currentForegroundWindowThreadId = NativeMethods.GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);
NativeMethods.AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);
NativeMethods.SetWindowPos(interopHelper.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);
NativeMethods.AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);
if (PassThroughNonNull(window).WindowState == WindowState.Minimized) PassThroughNonNull(window).WindowState = WindowState.Normal;
PassThroughNonNull(window).Show();
PassThroughNonNull(window).Focus(); // Changed from Activate(); due to flashing the window which is unwanted for this instance
}
static Window PassThroughNonNull(Window window)
{
if (window == null)
throw new ArgumentNullException(window.ToString());
return window;
}
}
}
internal static class NativeMethods
{
#region Imports
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)] // For 32 bit U1
internal static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, [MarshalAs(UnmanagedType.Bool)] bool fAttach); // For 32 bit U1
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)] // For 32 bit U1
internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
#endregion
}
// Use this to activate it
Focus(); // I use this to make sure it has focus but not needed to bring the window to the top
SystemWindows.GlobalActivate(this);
// Can also be used at startup to make sure it starts on top
private void Window_ContentRendered(object sender, EventArgs e)
{
this.Topmost = false;
}
private void Window_Initialized(object sender, EventArgs e)
{
this.Topmost = true;
Focus();
SystemWindows.GlobalActivate(this);
}
System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();
private Font verdana10Font;
private StreamReader reader;
private void SendToPrinter(string filename)
{
reader = new StreamReader(filename);
verdana10Font = new Font("Verdana", 10);
PrintDialog printDialog = new PrintDialog();
printDialog.ShowDialog();
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printDialog.PrinterSettings;
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
pd.Print();
if (reader != null)
reader.Close();
File.Delete(filename);
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
{
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ppeArgs.MarginBounds.Left;
float topMargin = ppeArgs.MarginBounds.Top;
string line = null;
linesPerPage = ppeArgs.MarginBounds.Height / verdana10Font.GetHeight(g);
while (count < linesPerPage && ((line = reader.ReadLine()) != null))
{
yPos = topMargin + (count * verdana10Font.GetHeight(g));
g.DrawString(line, verdana10Font, Brushes.Black, leftMargin, yPos, new StringFormat());
count++;
}
if (line != null)
{
ppeArgs.HasMorePages = true;
}
else
{
ppeArgs.HasMorePages = false;
}
}
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
string arguments = "";
proc.StartInfo.Arguments = arguments;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "schtasks.exe";
proc.Start();
proc.WaitForExit();
System.Threading.Thread.Sleep(5000);
bool running = true;
while (running)
{
if (Process.GetProcessesByName("CLOS2").Length == 0)
{
running = false;
Environment.Exit(0);
}
else
{
System.Threading.Thread.Sleep(1000);
}
}
//or use
private static string ExecCommand(string filename, string arguments)
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo(filename);
psi.Arguments = arguments;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
process.StartInfo = psi;
StringBuilder output = new StringBuilder();
process.OutputDataReceived += (sender, e) => { output.AppendLine(e.Data); };
process.ErrorDataReceived += (sender, e) => { output.AppendLine(e.Data); };
// run the process
process.Start();
// start reading output to events
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// wait for process to exit
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception("Command " + psi.FileName + " returned exit code " + process.ExitCode);
return output.ToString();
}
namespace pBarBW
{
public partial class Form1 : Form
{
ProgressBar progressBar1 = new ProgressBar();
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
public Form1()
{
InitializeComponent();
InitializeComponent();
Shown += new EventHandler(Form1_Shown);
// To report progress from the background worker we need to set this property
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(progressBar1);
}
}
}
private static void RunCommand(string directory, string filename, string args)
{
using (Process process = new Process())
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
UseShellExecute = false,
StandardOutputEncoding = Encoding.GetEncoding(437),
WorkingDirectory = directory,
FileName = filename,
Arguments = args
};
process.EnableRaisingEvents = true;
process.EnableRaisingEvents = true;
process.StartInfo = startInfo;
process.Exited += new EventHandler(ProcExited);
process.ErrorDataReceived += Proc_DataReceived;
process.OutputDataReceived += Proc_DataReceived;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
}
}
private static void Proc_DataReceived(object sender, DataReceivedEventArgs e)
{
EasyLogger.Info(e.Data);
}
private static void ProcExited(object sender, EventArgs e)
{
EasyLogger.Info("Process Exited..." + Environment.NewLine);
}
// NativeMethods Class
using System;
using System.Runtime.InteropServices;
namespace RefreshNotificationArea
{
internal class NativeMethods
{
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass,
string lpszWindow);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
}
}
// Main
using System;
namespace RefreshNotificationArea
{
class Program
{
static void Main(string[] args)
{
RefreshTrayArea();
}
public static void RefreshTrayArea()
{
IntPtr systemTrayContainerHandle = NativeMethods.FindWindow("Shell_TrayWnd", null);
IntPtr systemTrayHandle = NativeMethods.FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, "TrayNotifyWnd", null);
IntPtr sysPagerHandle = NativeMethods.FindWindowEx(systemTrayHandle, IntPtr.Zero, "SysPager", null);
IntPtr notificationAreaHandle = NativeMethods.FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "Notification Area");
if (notificationAreaHandle == IntPtr.Zero)
{
notificationAreaHandle = NativeMethods.FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32",
"User Promoted Notification Area");
IntPtr notifyIconOverflowWindowHandle = NativeMethods.FindWindow("NotifyIconOverflowWindow", null);
IntPtr overflowNotificationAreaHandle = NativeMethods.FindWindowEx(notifyIconOverflowWindowHandle, IntPtr.Zero,
"ToolbarWindow32", "Overflow Notification Area");
RefreshTrayArea(overflowNotificationAreaHandle);
}
RefreshTrayArea(notificationAreaHandle);
}
private static void RefreshTrayArea(IntPtr windowHandle)
{
const uint wmMousemove = 0x0200;
NativeMethods.GetClientRect(windowHandle, out NativeMethods.RECT rect);
for (var x = 0; x < rect.right; x += 5)
{
for (var y = 0; y < rect.bottom; y += 5)
{
NativeMethods.SendMessage(windowHandle, wmMousemove, 0, (y << 16) + x);
}
}
}
}
}
// Create key
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names");
key.SetValue("Name", "Isabella");
key.Close();
// Delete or close the new subkey.
Console.Write("\nDelete newly created registry key? (Y/N) ");
if(Char.ToUpper(Convert.ToChar(Console.Read())) == 'Y')
{
Registry.CurrentUser.DeleteSubKeyTree("Test9999");
Console.WriteLine("\nRegistry key {0} deleted.",
test9999.Name);
}
else
{
Console.WriteLine("\nRegistry key {0} closed.",
test9999.ToString());
test9999.Close();
}
Text = Resources.ResourceManager.GetString("ShadowEx");
// or
var message = Properties.Resources.ResourceManager.GetString("EnterMessage");
var title = Properties.Resources.ResourceManager.GetString("EnterTitle");
MessageBox.Show(message, title, MessageBoxButton.OK ,MessageBoxImage.Information);
// Image
Image = Resources.cmd.ToBitmap(),
using System;
using System.Collections.Generic;
namespace read_input_stream
{
// parser state to switch between checking and reading
enum ParserState
{
CheckForPrefix,
ReadQRCode
}
class Program
{
// static variables, could be encapuslated into a class object
// could also read values such as the prefix from a config file
const int qrCodeLength = 10;
const string prefix = "UID#";
static ParserState state = ParserState.CheckForPrefix;
static char[] rollingArray = new char[prefix.Length];
static List<char> qrCodeBuilder;
static void Main(string[] args)
{
Console.WriteLine("Type a string and then hit enter:");
var fakeStream = Console.ReadLine().ToCharArray();
foreach (var value in fakeStream)
{
// process one char value at a time
// allows using any stream of data
ProcessNextChar(value);
}
System.Console.WriteLine("... Done.");
}
private static void ProcessNextChar(char value)
{
// based on program state either use next chart to
// watch for known prefix or read QR code from input
switch (state)
{
case ParserState.CheckForPrefix:
CheckForPrefixMethod(value);
break;
case ParserState.ReadQRCode:
ReadQRCodeMethod(value);
break;
default:
System.Console.WriteLine($"Invalid ParserState: {state}");
break;
}
}
private static void CheckForPrefixMethod(char value)
{
// shift chars
for (int i = 0; i < rollingArray.Length; i++)
{
var nextIndex = i + 1;
if (nextIndex < rollingArray.Length)
{
rollingArray[i] = rollingArray[i + 1];
}
}
// add to end
rollingArray[rollingArray.Length - 1] = value;
// compare to known prefix
// if match change state
var rollingInputString = new string(rollingArray);
if(rollingInputString == prefix)
{
state = ParserState.ReadQRCode;
}
}
private static void ReadQRCodeMethod(char value)
{
// ensure we have a list to work with
if(qrCodeBuilder == null)
{
qrCodeBuilder = new List<char>(qrCodeLength);
}
// add char to list
qrCodeBuilder.Add(value);
if(qrCodeBuilder.Count == qrCodeLength)
{
// event to save qrCode id to database
System.Console.WriteLine($"QR Code: {new string(qrCodeBuilder.ToArray())}");
// clear our builder for the next qr code
qrCodeBuilder.Clear();
// change state back to checking for prefix
state = ParserState.CheckForPrefix;
}
}
}
}
using System;
using System.Diagnostics;
using System.IO;
namespace NightMode
{
class TasksSchedule
{
static bool taskexistance(string taskname)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "schtasks.exe";
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.WindowStyle = ProcessWindowStyle.Hidden;
start.Arguments = "/query /TN " + taskname;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stdout = reader.ReadToEnd();
if (stdout.Contains(taskname))
{
return true;
}
else
{
return false;
}
}
}
}
}
}
// in your main
// SCHTASKS /Create /RU "NT AUTHORITY\SYSTEM" /TN "Notepad" /TR "C:\windows\system32\notepad.exe"
if (!TasksSchedule.taskexistance("NightMode"))
{
using (Process proc = new Process())
{
string SYSTEM = "\"NT AUTHORITY\\SYSTEM\"";
string TaskPath = "\"" + AssemblyDirectory + "\\NightMode.exe\"";
string TaskName = "\"NightMode\"";
string arguments = "/Create /RU " + SYSTEM + " /TN " + TaskName + " / TR " + TaskPath;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.FileName = "schtasks.exe";
proc.Start();
proc.WaitForExit();
}
}
// or
var arguments = "/Run /Tn " + "NightMode";
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
FileName = "SCHTASKS.exe",
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = arguments
}
};
p.Start();
using System.ServiceProcess;
using System.Threading;
namespace SCTracerService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Service1 myService = new Service1();
myService.OnDebug();
Thread.Sleep(Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
// In Service1
internal void OnDebug()
{
}
using System.ServiceProcess;
private string IsServiceRunning(string service)
{
ServiceController sc = new ServiceController(service);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
}
IntPtr hWnd = WindowHelper.FindWindow(null, "Sticky Pad");
WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);
WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_NO_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);
public static class WindowHelper
{
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NO_TOPMOST = new IntPtr(-2);
public const UInt32 SWP_NOSIZE = 0x0001;
public const UInt32 SWP_NOMOVE = 0x0002;
public const UInt32 SWP_SHOWWINDOW = 0x0040;
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
}
// Reference to "Microsoft Shell Control And Automation"
public static string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return string.Empty;
}
// Mutex
private static Mutex mutex;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
var assembly = typeof(Program).Assembly;
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
var id = attribute.Value;
var mutex = new Mutex(true, id);
if (mutex.WaitOne(TimeSpan.Zero, true))
{
try
{
startApp();
}
finally
{
mutex.ReleaseMutex();
}
}
else
{
exitApp();
}
}
// or
using System;
using System.Diagnostics;
namespace APP_NAME
{
public class SingleInstance
{
internal static void Check()
{
foreach (Process proc in Process.GetProcessesByName("PROCESS_NAME"))
{
IntPtr hWnd = WindowHelper.FindWindow(null, "WINDOW_TITLE"); // Make sure the window title is unique or it will find the first one
WindowHelper.GetWindowThreadProcessId(hWnd, out uint id);
if (id != 0)
{
if (id != Process.GetCurrentProcess().Id)
{
WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);
WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_NO_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);
WindowHelper.SetForegroundWindow(hWnd);
Environment.Exit(0);
}
}
}
}
}
}
namespace APP_NAME
{
public static class WindowHelper
{
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NO_TOPMOST = new IntPtr(-2);
public const UInt32 SWP_NOSIZE = 0x0001;
public const UInt32 SWP_NOMOVE = 0x0002;
public const UInt32 SWP_SHOWWINDOW = 0x0040;
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
}
// or
// Initialize(); from main/form/window
private void Initialize()
{
if (!CreateSingleInstance(
Assembly.GetExecutingAssembly().GetName().Name,
SingleInstanceCallback)) return;
InitializeComponent();
}
static EventWaitHandle eventWaitHandle;
private void SingleInstanceCallback(object sender, InstanceCallbackEventArgs args)
{
if (InstanceCallbackEventArgs.CommandLineArgs.Length > 1)
{
if (InstanceCallbackEventArgs.CommandLineArgs[1] == "--start")
{
DisplayChanged(null, null);
}
else if (InstanceCallbackEventArgs.CommandLineArgs[1] == "--shutdown")
{
// Do Cleanup here
Environment.Exit(0);
}
}
}
private static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback)
{
string eventName = string.Format("{0}-{1}", Environment.MachineName, name);
InstanceProxy.IsFirstInstance = false;
InstanceProxy.CommandLineArgs = Environment.GetCommandLineArgs();
try
{
eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
}
catch
{
InstanceProxy.IsFirstInstance = true;
}
if (InstanceProxy.IsFirstInstance)
{
eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);
ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false);
eventWaitHandle.Close();
RegisterRemoteType(name);
}
else
{
UpdateRemoteObject(name);
if (eventWaitHandle != null) eventWaitHandle.Set();
Environment.Exit(0);
}
return InstanceProxy.IsFirstInstance;
}
private static void UpdateRemoteObject(string uri)
{
var clientChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(clientChannel, true);
var proxy =
Activator.GetObject(typeof(InstanceProxy),
string.Format("ipc://{0}{1}/{1}", Environment.MachineName, uri)) as InstanceProxy;
if (proxy != null)
proxy.SetCommandLineArgs(InstanceProxy.IsFirstInstance, InstanceProxy.CommandLineArgs);
ChannelServices.UnregisterChannel(clientChannel);
}
private static void RegisterRemoteType(string uri)
{
var serverChannel = new IpcServerChannel(Environment.MachineName + uri);
ChannelServices.RegisterChannel(serverChannel, true);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(InstanceProxy), uri, WellKnownObjectMode.Singleton);
Process process = Process.GetCurrentProcess();
process.Exited += delegate { ChannelServices.UnregisterChannel(serverChannel); };
}
private static void WaitOrTimerCallback(object state, bool timedOut)
{
var callback = state as EventHandler<InstanceCallbackEventArgs>;
if (callback == null) return;
callback(state,
new InstanceCallbackEventArgs(InstanceProxy.IsFirstInstance,
InstanceProxy.CommandLineArgs));
}
// Classes
public class InstanceProxy : MarshalByRefObject
{
internal static bool IsFirstInstance;
internal static string[] CommandLineArgs;
public void SetCommandLineArgs(bool isFirstInstance, string[] commandLineArgs)
{
IsFirstInstance = isFirstInstance;
CommandLineArgs = commandLineArgs;
}
}
public class InstanceCallbackEventArgs : EventArgs
{
internal static bool IsFirstInstance;
internal static string[] CommandLineArgs;
internal InstanceCallbackEventArgs(bool isFirstInstance, string[] commandLineArgs)
{
IsFirstInstance = isFirstInstance;
CommandLineArgs = commandLineArgs;
}
}
try
{
Process proc = new Process();
proc.StartInfo.Arguments = "\"" + args[0] + "\"";
proc.StartInfo.FileName = @"C:\Program Files\Unlocker\Unlocker.exe";
proc.StartInfo.Verb = "runas";
proc.Start();
proc.WaitForExit();
SendRefresh = false;
}
catch (System.ComponentModel.Win32Exception ex) { MessageBox.Show(ex.Message, "The operation was cancelled."); }
// or
string args = "args";
string program = "/C sc start" + " " + args;
using (Process proc = new Process())
{
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.Arguments = program;
proc.StartInfo.Verb = "runas"; // run as admin
proc.Start();
proc.WaitForExit();
}
EasyLogger.Info("Arguments: " + args[0].NullIfEmpty() ?? string.Empty + args[2].NullIfEmpty() ?? string.Empty + args[3].NullIfEmpty() ?? string.Empty + args[4].NullIfEmpty() ?? string.Empty);
public static class StringExtensions
{
public static string NullIfEmpty(this string s)
{
return string.IsNullOrEmpty(s) ? null : s;
}
public static string NullIfWhiteSpace(this string s)
{
return string.IsNullOrEmpty(s) ? null : s;
}
}
// Get first 3 letter from string
char[] array = BarcodeDataTemp.Take(3).ToArray();
// or
string str = BarcodeDataTemp.Substring(0, 5);
// or with error checking
string UIDTemp = null;
if(!string.IsNullOrEmpty(BarcodeDataTemp) && BarcodeDataTemp.Length >= 3)
UIDTemp = BarcodeDataTemp.Substring(0, 3);
// Split
char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine($"Original text: '{text}'");
string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");
foreach (var word in words)
{
System.Console.WriteLine($"<{word}>");
}
// Split
string somestring = "this is some text that is here!";
somestring.Split(new[] { "some text" }, StringSplitOptions.None)[0]
somestring.Split(new[] { "some text" }, StringSplitOptions.None)[1]
// or
string[] args = arg.Split(',');
substring = str.Split(',')[0];
Thread thread = new Thread(() => Begin(args))
{
IsBackground = true
};
thread.Start();
Form form;
using (form = new Form())
{
form.Opacity = 0.0;
form.TopMost = true;
form.Show();
form.Activate();
var dialogResult = System.Windows.Forms.MessageBox.Show(form, "Are you sure you want to put your PC into NightMode?", "NightMode", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == System.Windows.Forms.DialogResult.Yes)
{
}
}
// or
Message("Installation completed successfully!", "Register" , MessageBoxButtons.OK, MessageBoxIcon.Information);
static void Message(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
{
Form form;
using (form = new Form())
{
form.TopMost = true;
MessageBox.Show(form, message, title, buttons, icon);
}
}
// or
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon icon = MessageBoxIcon.Error;
string message = Resources.ResourceManager.GetString("MESSAGE");
string caption = Resources.ResourceManager.GetString("TITLE");
DialogResult result = null;
Form form;
using (form = new Form())
{
form.TopMost = true;
MessageBox.Show(form, caption, message, buttons, icon);
}
if (result == DialogResult.Yes)
{
// do something with the result
}
// or
//class
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace TopMostMessageBox
{
/// <summary>
/// Displays MessageBox messages as a top most window
/// </summary>
static public class TopMostMessageBox
{
/// <summary>
/// Displays a <see cref="MessageBox"/> but as a TopMost window.
/// </summary>
/// <param name="message">The text to appear in the message box.</param>
/// <param name="title">The title of the message box.</param>
/// <returns>The button pressed.</returns>
/// <remarks>This will display with no title and only the OK button.</remarks>
static public DialogResult Show(string message)
{
return Show(message, string.Empty, MessageBoxButtons.OK);
}
/// <summary>
/// Displays a <see cref="MessageBox"/> but as a TopMost window.
/// </summary>
/// <param name="message">The text to appear in the message box.</param>
/// <param name="title">The title of the message box.</param>
/// <returns>The button pressed.</returns>
/// <remarks>This will display with only the OK button.</remarks>
static public DialogResult Show(string message, string title)
{
return Show(message, title, MessageBoxButtons.OK);
}
/// <summary>
/// Displays a <see cref="MessageBox"/> but as a TopMost window.
/// </summary>
/// <param name="message">The text to appear in the message box.</param>
/// <param name="title">The title of the message box.</param>
/// <param name="buttons">The buttons to display in the message box.</param>
/// <returns>The button pressed.</returns>
static public DialogResult Show(string message, string title, MessageBoxButtons buttons)
{
// Create a host form that is a TopMost window which will be the parent of the MessageBox.
Form topmostForm = new Form();
// We do not want anyone to see this window so position it off the visible screen and make it as small as possible
topmostForm.Size = new System.Drawing.Size(1, 1);
topmostForm.StartPosition = FormStartPosition.Manual;
System.Drawing.Rectangle rect = SystemInformation.VirtualScreen;
topmostForm.Location = new System.Drawing.Point(rect.Bottom + 10, rect.Right + 10);
topmostForm.Show();
// Make this form the active form and make it TopMost
topmostForm.Focus();
topmostForm.BringToFront();
topmostForm.TopMost = true;
topmostForm.Activate();
// Finally show the MessageBox with the form just created as its owner
DialogResult result = MessageBox.Show(topmostForm, message, title, buttons);
topmostForm.Dispose(); // clean it up all the way
return result;
}
}
}
//program
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace TopMostMessageBox
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
MessageBox.Show(args[i]);
}
}
}
}
//Server
using System.Net;
using System.Net.Sockets;
string xName = "string to send";
byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(xName);
string IP = "127.0.0.1";
int port = 80;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
//Client
using System.Net;
using System.Net.Sockets;
using System.Collections.Specialized;
using System.Linq;
private static Exception socketException = null;
static void OpenSocket()
{
byte[] data = new Byte[256];
IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
WinSocket.ReceiveTimeout = 0;
WinSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
WinSocket.Bind(ServerEndPoint);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
int recv = WinSocket.ReceiveFrom(data, ref Remote);
string DataRecieved = Encoding.ASCII.GetString(data, 0, recv);
}
// Standard WPF Window: To Show the Window
// Minimize the Window First then Hide
ThisWindow.WindowState = WindowState.Minimized;
ThisWindow.Hide();
// Show the Window again (A LOT OF WORK JUST TO SHOW A WINDOW)
ThisWindow.Opacity = 0;
ThisWindow.Topmost = true;
ThisWindow.WindowState = WindowState.Normal;
ThisWindow.Show();
ThisWindow.WindowState = WindowState.Minimized;
ThisWindow.BringIntoView();
ThisWindow.Activate();
ThisWindow.Topmost = false;
ThisWindow.Opacity = 1;
ThisWindow.WindowState = WindowState.Normal;
// ALL OF THE BELOW USES PINVOKE
static class RelativeWindows
{
public static void SetPlacement(this Window window, string placementXml)
{
WindowPlacement.SetPlacement(new WindowInteropHelper(window).Handle, placementXml);
}
public static string GetPlacement(this Window window)
{
return WindowPlacement.GetPlacement(new WindowInteropHelper(window).Handle);
}
}
// NativeMethods
// WINDOW_PLACEMENT
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT(int left, int top, int right, int bottom)
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
public POINT minPosition;
public POINT maxPosition;
public RECT normalPosition;
}
public static class WindowPlacement
{
private static Encoding encoding = new UTF8Encoding();
private static XmlSerializer serializer = new XmlSerializer(typeof(WINDOWPLACEMENT));
[DllImport("user32.dll")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
private static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
public static void SetPlacement(IntPtr windowHandle, string placementXml)
{
if (string.IsNullOrEmpty(placementXml))
{
return;
}
WINDOWPLACEMENT placement;
byte[] xmlBytes = encoding.GetBytes(placementXml);
try
{
using (MemoryStream memoryStream = new MemoryStream(xmlBytes))
{
placement = (WINDOWPLACEMENT)serializer.Deserialize(memoryStream);
}
placement.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
placement.flags = 0;
placement.showCmd = (placement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWNORMAL : placement.showCmd);
SetWindowPlacement(windowHandle, ref placement);
}
catch (InvalidOperationException)
{
// Parsing placement XML failed. Fail silently.
}
}
public static string GetPlacement(IntPtr windowHandle)
{
WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
GetWindowPlacement(windowHandle, out placement);
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
{
serializer.Serialize(xmlTextWriter, placement);
byte[] xmlBytes = memoryStream.ToArray();
return encoding.GetString(xmlBytes);
}
}
}
// WINDOW_TO_FRONT
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NO_TOPMOST = new IntPtr(-2);
public const UInt32 SWP_NOSIZE = 0x0001;
public const UInt32 SWP_NOMOVE = 0x0002;
public const UInt32 SWP_SHOWWINDOW = 0x0040;
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
<!-- Static Object -->
((MainWindow)Application.Current.MainWindow).image.Source
= new BitmapImage(new Uri(...));
<!-- START GET ARGS -->
<!-- App.Xaml -->
<Application x:Class="Tasks.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
Startup="App_Startup">
<Application.Resources>
</Application.Resources>
</Application>
<!-- App.Xaml.cs -->
private void App_Startup(object sender, StartupEventArgs e)
{
for (int i = 0; i != e.Args.Length; ++i)
{
if (e.Args[i] == "/settings")
{
// Do something with settings
}
}
}
<!-- SINGLE INSTANCE: App.Xaml.cs -->
private void App_Startup(object sender, StartupEventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
var id = attribute.Value;
var mutex = new Mutex(true, id);
if (mutex.WaitOne(TimeSpan.Zero, true))
{
try
{
startApp();
}
finally
{
mutex.ReleaseMutex();
}
}
else
{
exitApp();
}
}
<!-- END GET ARGS -->
<!-- Resize Window (WindowStyle="None") -->
<!-- MainWindow.xaml -->
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
<!-- App.xaml -->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles.xaml"/>
<ResourceDictionary Source="Resources/Icons.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<!-- MainWindow.xaml -->
<Window.Background>
<SolidColorBrush Opacity="0.9" Color="Black"/>
</Window.Background>
<!-- MainWindow -->
<Window x:Class="Tasks.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Name="window" Title="Tasks" Height="400" Width="500" AllowsTransparency="True"
WindowStyle="None" WindowStartupLocation="CenterScreen" BorderThickness="1" BorderBrush="#FF292929">
<Grid>
<StackPanel>
<StackPanel Background="Black">
<!-- CLOSE -->
<Button x:Name="CloseButton" Style="{StaticResource ControlBoxButtons}" Height="28" Width="44" ToolTip="Close" ToolTipService.InitialShowDelay="1000" ToolTipService.ShowDuration="2500" ToolTipService.BetweenShowDelay="0" Cursor="Hand" HorizontalAlignment="Right" VerticalAlignment="Top" Click="CloseButton_Click">
<Path Fill="{Binding ElementName=CloseButton, Path=Foreground}" Width="12" Data="{StaticResource CloseIcon}" Stretch="Uniform"/>
</Button>
</StackPanel>
<StackPanel Height="370" Background="#212121">
</StackPanel>
</StackPanel>
</Grid>
</Window>
<!-- START STYLES -->
<!-- Resources/Styles.xaml -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Button Styles -->
<Style x:Key="ControlBoxButtons" TargetType="Button">
<Setter Property="Focusable" Value="False"/>
<Setter Property="Background" Value="Black"/>
<Setter Property="Foreground" Value="#FFEAEAEA"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" Padding="0" BorderThickness="0">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Grid x:Name="visibilityGrid" Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="visibilityGrid" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#1B1B1B"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="#333333"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
<!-- Resources/Icons.xaml -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<PathGeometry x:Key="CloseIcon">
M6.998 0L0.005 6.997 105.263 112.254 0.005 217.512l6.993 7 105.258 -105.272 105.265 105.272 6.986 -7L119.249 112.254 224.507 6.997 217.521 0 112.256 105.258Z
</PathGeometry>
</ResourceDictionary>
<!-- END STYLES -->
<!-- Static Controls -->
<ContentControl>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Window buttons -->
<Geometry x:Key="Restore">F1M0,2L0,10 8,10 8,2 0,2 0,3 7,3 7,9 1,9 1,3 M2,0L2,3 8,3 8,8 10,8 10,0 2,0 2,1 9,1 9,7 8,7 8,3 3,3 3,1z</Geometry>
<Geometry x:Key="Maximize">F1M0,0L0,10 10,10 10,0 0,0 0,1 9,1 9,9 1,9 1,1z</Geometry>
<Geometry x:Key="Close">F1M0.6,0L10,9.4 9.4,10 0,0.6 0.6,0 M9.4,0L10,0.6 0.6,10 0,9.4 9.4,0z</Geometry>
<Geometry x:Key="Minimize">M0,0 L8,0 8,1 8,2 0,2 0,1 z</Geometry>
</ResourceDictionary>
foreach (Control c in panel1.Children)
{
if (c.GetType() == typeof(Button))
{
c.Background = Brushes.Transparent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment