Setting Cloud Linux Server
http://aws.amazon.com/ec2/
Setting up GCC in Linux
http://www.cyberciti.biz/faq/centos-linux-install-gcc-c-c-compiler/ (G++ V4.4)
http://unix.stackexchange.com/questions/63587/how-to-install-g-4-7-2-c11-on-centos-5-x (G++ V4.7)
Tuesday, July 15, 2014
Wednesday, May 28, 2014
How to show console in winForms?
using System.Runtime.InteropServices;
private void Form1_Load(object sender, EventArgs e)
{
AllocConsole();
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
Thursday, May 22, 2014
How to create events?
namespace MyFormNamespace
{
public partial class MyForm : Form
{
public MyForm()
{
MyEventArg e = new MyEventArg ();
e.Number = 1;
e.Message = "hello!";
OnMyEventReceived(e); //activate the event!
}
public event EventHandler<MyEventArg > MyEvent;
protected void OnMyEventReceived(MyEventArg e)
{
if (this.InvokeRequired)
{
MethodInvoker invoker = () => OnMyEventReceived(e);
this.Invoke(invoker);
}
else
{
EventHandler<MyEventArg> handler = MyEvent;
if (handler != null)
{
handler(this, e);
}
}
}
public class MyEventArg : EventArgs
{
public int Number;
public string Message;
}
}
//########## Another program ##########
using MyForm;
namespace MyForm2Namespace
{
public partial class MyForm2 : Form
{
public MyForm2()
{
MyForm firstForm = new MyForm();
firstForm.MyEvent += myCallbackMethod; //register for the event
}
//myCallbackMethod() will be called when the event is activated in the first form
private void myCallbackMethod(object sender, MyEventArg e)
{
richTextBox1.Text += e.Number.ToString() + "\n";
richTextBox1.Text += e.Message + "\n\n";
}
}
}
{
public partial class MyForm : Form
{
public MyForm()
{
MyEventArg e = new MyEventArg ();
e.Number = 1;
e.Message = "hello!";
OnMyEventReceived(e); //activate the event!
}
public event EventHandler<MyEventArg > MyEvent;
protected void OnMyEventReceived(MyEventArg e)
{
if (this.InvokeRequired)
{
MethodInvoker invoker = () => OnMyEventReceived(e);
this.Invoke(invoker);
}
else
{
EventHandler<MyEventArg> handler = MyEvent;
if (handler != null)
{
handler(this, e);
}
}
}
public class MyEventArg : EventArgs
{
public int Number;
public string Message;
}
}
//########## Another program ##########
using MyForm;
namespace MyForm2Namespace
{
public partial class MyForm2 : Form
{
public MyForm2()
{
MyForm firstForm = new MyForm();
firstForm.MyEvent += myCallbackMethod; //register for the event
}
//myCallbackMethod() will be called when the event is activated in the first form
private void myCallbackMethod(object sender, MyEventArg e)
{
richTextBox1.Text += e.Number.ToString() + "\n";
richTextBox1.Text += e.Message + "\n\n";
}
}
}
Tuesday, May 13, 2014
RTD data to C# program
public partial class Form1 : Form
{
//######################## RTD METHODS ########################
// Test harness that emulates the interaction of
// Excel with an RTD server.
void processRTD()
{
//RTD
int topicID = 100;
const String RTDProgID = "esrtd";
const String topic1 = "HSI J2-HKF";
bool firstUpdate = true;
try
{
Object ret;
// Create the RTD server.
Type rtd;
Object rtdServer = null;
rtd = Type.GetTypeFromProgID(RTDProgID);
rtdServer = Activator.CreateInstance(rtd);
IRtdServer server = rtdServer as IRtdServer;
// Create the updateEvent.
UpdateEvent updateEvent = new UpdateEvent();
ret = server.ServerStart(updateEvent);
// Connect Data.
Object[] topics = new Object[2];
topics[0] = topic1;
topicID++;
topics[1] = "Bid Size";
ret = server.ConnectData(topicID, topics, true);
topicID++;
topics[1] = "Bid";
ret = server.ConnectData(topicID, topics, true);
topicID++;
topics[1] = "Ask";
ret = server.ConnectData(topicID, topics, true);
topicID++;
topics[1] = "Ask Size";
ret = server.ConnectData(topicID, topics, true);
// Loop and wait for RTD to notify (via callback) that
// data is available.
int status = 1;
int topicCount = 4;
double value;
Object[,] r = new Object[2, 4];
while (status == 1 && !_shouldStop)
{
// Check that the RTD server is still alive.
status = server.Heartbeat();
// Get data from the RTD server.
r = server.RefreshData(topicCount);
if (r.Length > 0)
{
for (int i = 0; i < r.Length / 2; i++)
{
value = 0;
double.TryParse(r[1, i].ToString(), out value);
switch (r[0, i].ToString())
{
case bidQtyCode:
marketData.bestBidQty = value;
break;
case bidCode:
marketData.bestBid = value;
break;
case askCode:
marketData.bestAsk = value;
break;
case askQtyCode:
marketData.bestAskQty = value;
break;
}
}
updateDisplay(marketData);
if (firstUpdate)
{
firstUpdate = false;
resizeLadder();
}
}
Thread.Sleep(100);
}
// Disconnect from data topic.
server.DisconnectData(topicID);
// Shutdown the RTD server.
server.ServerTerminate();
}
catch {}
}
public class UpdateEvent : IRTDUpdateEvent
{
public long Count { get; set; }
public int HeartbeatInterval { get; set; }
public UpdateEvent()
{
// Do not call the RTD Heartbeat()
// method.
HeartbeatInterval = -1;
}
public void Disconnect()
{
// Do nothing.
}
public void UpdateNotify()
{
Count++;
}
}
private void button1_Click(object sender, EventArgs e)
{
m_GAPI.sendMsg(textBox1.Text);
}
}
// Form1 Class Ends
public class MarketData
{
private double _bestBid, _bestAsk, _bestBidQty, _bestAskQty;
public double bestBid
{
get { return _bestBid; }
set { _bestBid = value; }
}
public double bestAsk
{
get { return _bestAsk; }
set { _bestAsk = value; }
}
public double bestBidQty
{
get { return _bestBidQty; }
set { _bestBidQty = value; }
}
public double bestAskQty
{
get { return _bestAskQty; }
set { _bestAskQty = value; }
}
}
[ComImport,
TypeLibType((short)0x1040),
Guid("EC0E6191-DB51-11D3-8F3E-00C04F3651B8")]
public interface IRtdServer
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(10)]
int ServerStart([In, MarshalAs(UnmanagedType.Interface)] IRTDUpdateEvent callback);
[return: MarshalAs(UnmanagedType.Struct)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
object ConnectData([In] int topicId, [In, MarshalAs(UnmanagedType.SafeArray,
SafeArraySubType = VarEnum.VT_VARIANT)] ref object[] parameters, [In, Out] ref bool newValue);
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(12)]
object[,] RefreshData([In, Out] ref int topicCount);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(13)]
void DisconnectData([In] int topicId);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(14)]
int Heartbeat();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(15)]
void ServerTerminate();
}
[ComImport,
TypeLibType((short)0x1040),
Guid("A43788C1-D91B-11D3-8F39-00C04F3651B8")]
public interface IRTDUpdateEvent
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(10),
PreserveSig]
void UpdateNotify();
[DispId(11)]
int HeartbeatInterval
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
get;
[param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(12)]
void Disconnect();
}
}
Thursday, February 20, 2014
How to communicate between forms?
Form2.cs:
private Form1 mainForm = null;
public Form2(Form callingForm) //put the calling form as arg
{
InitializeComponent();
mainForm = callingForm as Form1;
}
Form1.cs
private Form2 subForm = null;
subForm = new Form2(this);
subForm.show();
private Form1 mainForm = null;
public Form2(Form callingForm) //put the calling form as arg
{
InitializeComponent();
mainForm = callingForm as Form1;
}
Form1.cs
private Form2 subForm = null;
subForm = new Form2(this);
subForm.show();
Wednesday, February 19, 2014
How to use threading with buffer (with correct way of terminating the thread)?
using System.Threading;
namespace Form1
{
public partial class Form1: Form
{
//Threading
private Thread processorThread = null;
private readonly object _locker = new object();
private volatile bool _shouldStop = false; //To exit thread cleanly
private Queue<int> buffer = new Queue<int>();
public Form1(Form callingForm, int formNum)
{
processorThread= new Thread(processNumber);
processorThread.IsBackground = true; //Thread will terminate automatically when program close
processorThread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_shouldStop = true;
processorThread.Interrupt();
processorThread.Join(3000);
}
private void processNumber()
{
int myNumber;
while (!_shouldStop)
{
try
{
lock (_locker)
{
if (buffer.Count == 0)
Monitor.Wait(_locker); //Releases the lock on an object and blocks the current thread until it reacquires the lock.
}
lock (_locker)
{
myNumber= buffer.Dequeue();
}
tsDictionary = displayNumber(myNumber);
}
catch (Exception err)
{
//MessageBox.Show(this, "processNumber(): " + err.Message);
}
}
}
private void number_Update(object sender, EventArgs e) //an imaginary event that send a random number on random time
{
try
{
if (e != null)
{
lock (_locker)
{
buffer.Enqueue(e.number);
Monitor.Pulse(_locker); //Notifies a thread in the waiting queue of a change in the locked object's state - i.e. "wake" the waiting thread
}
}
}
catch (Exception err)
{
}
}
void displayNumber(int number)
{
if (label1.InvokeRequired)
{
MethodInvoker invoker = () => displayNumber(number);
label1.Invoke(invoker);
}
else
label1.Text += " " + number.ToString();
}
}
}
namespace Form1
{
public partial class Form1: Form
{
//Threading
private Thread processorThread = null;
private readonly object _locker = new object();
private volatile bool _shouldStop = false; //To exit thread cleanly
private Queue<int> buffer = new Queue<int>();
public Form1(Form callingForm, int formNum)
{
processorThread= new Thread(processNumber);
processorThread.IsBackground = true; //Thread will terminate automatically when program close
processorThread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_shouldStop = true;
processorThread.Interrupt();
processorThread.Join(3000);
}
private void processNumber()
{
int myNumber;
while (!_shouldStop)
{
try
{
lock (_locker)
{
if (buffer.Count == 0)
Monitor.Wait(_locker); //Releases the lock on an object and blocks the current thread until it reacquires the lock.
}
lock (_locker)
{
myNumber= buffer.Dequeue();
}
tsDictionary = displayNumber(myNumber);
}
catch (Exception err)
{
//MessageBox.Show(this, "processNumber(): " + err.Message);
}
}
}
private void number_Update(object sender, EventArgs e) //an imaginary event that send a random number on random time
{
try
{
if (e != null)
{
lock (_locker)
{
buffer.Enqueue(e.number);
Monitor.Pulse(_locker); //Notifies a thread in the waiting queue of a change in the locked object's state - i.e. "wake" the waiting thread
}
}
}
catch (Exception err)
{
}
}
void displayNumber(int number)
{
if (label1.InvokeRequired)
{
MethodInvoker invoker = () => displayNumber(number);
label1.Invoke(invoker);
}
else
label1.Text += " " + number.ToString();
}
}
}
Tuesday, February 18, 2014
How to use custom cursor from resource?
using System.Runtime.InteropServices;
using System.IO;
namespace Form1
{
public partial class Form1: Form
{
private static System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(Form1.Properties.Resources.yl_cur);
private Cursor yellowCursor = LoadCursorFromResource(cursorMemoryStream);
this.Cursor = yellowCursor;
[DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern IntPtr LoadCursorFromFile(String str);
public static Cursor LoadCursorFromResource(System.IO.MemoryStream cursorMemoryStream)
{
using (var fileStream = File.Create(@".\tempCursor.cur"))
{
cursorMemoryStream.CopyTo(fileStream);
}
Cursor result = new Cursor(LoadCursorFromFile(@".\tempCursor.cur"));
File.Delete(@".\tempCursor.cur");
return result;
}
using System.IO;
namespace Form1
{
public partial class Form1: Form
{
private static System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(Form1.Properties.Resources.yl_cur);
private Cursor yellowCursor = LoadCursorFromResource(cursorMemoryStream);
this.Cursor = yellowCursor;
[DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern IntPtr LoadCursorFromFile(String str);
public static Cursor LoadCursorFromResource(System.IO.MemoryStream cursorMemoryStream)
{
using (var fileStream = File.Create(@".\tempCursor.cur"))
{
cursorMemoryStream.CopyTo(fileStream);
}
Cursor result = new Cursor(LoadCursorFromFile(@".\tempCursor.cur"));
File.Delete(@".\tempCursor.cur");
return result;
}
How to disable selection in DataGridView?
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
dataGridView1.CurrentCell.Selected = false;
}
{
dataGridView1.CurrentCell.Selected = false;
}
Thursday, February 6, 2014
How to disable close button on winForm?
using System.Runtime.InteropServices; //For "DllImportAttribute"
namespace Form1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CloseButton.EnableDisable(this, false);
}
class CloseButton
{
private const int SC_CLOSE = 0xF060;
private const int MF_GRAYED = 0x1;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern int EnableMenuItem(IntPtr hMenu, int wIDEnableItem, int wEnable);
public static void EnableDisable(Form form,bool isEnable)
{
EnableMenuItem(GetSystemMenu(form.Handle, isEnable), SC_CLOSE, MF_GRAYED);
}
}
}
namespace Form1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CloseButton.EnableDisable(this, false);
}
class CloseButton
{
private const int SC_CLOSE = 0xF060;
private const int MF_GRAYED = 0x1;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern int EnableMenuItem(IntPtr hMenu, int wIDEnableItem, int wEnable);
public static void EnableDisable(Form form,bool isEnable)
{
EnableMenuItem(GetSystemMenu(form.Handle, isEnable), SC_CLOSE, MF_GRAYED);
}
}
}
How to do Inter-Process Communication through Named Pipes?
Server.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Added
using System.IO.Pipes;
using System.IO;
using System.Threading;
using System.Security.Principal;
using server;
//using PipeServer;
namespace server
{
/// <summary>
/// PipeServer creates a listener thread and waits for messages from clients.
/// Received messages are displayed in Textbox
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tbox.Text = "";
Pipeserver.pipeName = "testpipe";
Pipeserver.owner = this;
//Pipeserver.ownerInvoker = new Invoker(this);
ThreadStart pipeThread = new ThreadStart(Pipeserver.createPipeServer);
Thread listenerThread = new Thread(pipeThread);
listenerThread.SetApartmentState(ApartmentState.STA);
listenerThread.IsBackground = true;
listenerThread.Start();
}
public void setTextbox(string text)
{
if (tbox.InvokeRequired)
{
MethodInvoker invoker = () => setTextbox(text);
tbox.Invoke(invoker);
}
else
{
tbox.Text = text;
}
}
}
public class Pipeserver
{
public static Form1 owner;
//public static Invoker ownerInvoker;
public static string pipeName;
private static NamedPipeServerStream pipeServer;
private static readonly int BufferSize = 256;
//private static void SetTextbox(String text)
//{
// owner.tbox.Text = String.Concat(owner.tbox.Text, text);
// if (owner.tbox.ExtentHeight > owner.tbox.ViewportHeight)
// {
// owner.tbox.ScrollToEnd();
// }
//}
public static void createPipeServer()
{
Decoder decoder = Encoding.Default.GetDecoder();
Byte[] bytes = new Byte[BufferSize];
char[] chars = new char[BufferSize];
int numBytes = 0;
StringBuilder msg = new StringBuilder();
//ownerInvoker.sDel = SetTextbox;
try
{
pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous);
while (true)
{
pipeServer.WaitForConnection();
do
{
msg.Length = 0;
do
{
numBytes = pipeServer.Read(bytes, 0, BufferSize);
if (numBytes > 0)
{
int numChars = decoder.GetCharCount(bytes, 0, numBytes);
decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
msg.Append(chars, 0, numChars);
}
} while (numBytes > 0 && !pipeServer.IsMessageComplete);
decoder.Reset();
if (numBytes > 0)
{
owner.setTextbox(msg.ToString());//ownerInvoker.Invoke(msg.ToString());
}
} while (numBytes != 0);
pipeServer.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Added
using System.IO.Pipes;
using System.IO;
using System.Threading;
using System.Security.Principal;
using server;
//using PipeServer;
namespace server
{
/// <summary>
/// PipeServer creates a listener thread and waits for messages from clients.
/// Received messages are displayed in Textbox
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tbox.Text = "";
Pipeserver.pipeName = "testpipe";
Pipeserver.owner = this;
//Pipeserver.ownerInvoker = new Invoker(this);
ThreadStart pipeThread = new ThreadStart(Pipeserver.createPipeServer);
Thread listenerThread = new Thread(pipeThread);
listenerThread.SetApartmentState(ApartmentState.STA);
listenerThread.IsBackground = true;
listenerThread.Start();
}
public void setTextbox(string text)
{
if (tbox.InvokeRequired)
{
MethodInvoker invoker = () => setTextbox(text);
tbox.Invoke(invoker);
}
else
{
tbox.Text = text;
}
}
}
public class Pipeserver
{
public static Form1 owner;
//public static Invoker ownerInvoker;
public static string pipeName;
private static NamedPipeServerStream pipeServer;
private static readonly int BufferSize = 256;
//private static void SetTextbox(String text)
//{
// owner.tbox.Text = String.Concat(owner.tbox.Text, text);
// if (owner.tbox.ExtentHeight > owner.tbox.ViewportHeight)
// {
// owner.tbox.ScrollToEnd();
// }
//}
public static void createPipeServer()
{
Decoder decoder = Encoding.Default.GetDecoder();
Byte[] bytes = new Byte[BufferSize];
char[] chars = new char[BufferSize];
int numBytes = 0;
StringBuilder msg = new StringBuilder();
//ownerInvoker.sDel = SetTextbox;
try
{
pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous);
while (true)
{
pipeServer.WaitForConnection();
do
{
msg.Length = 0;
do
{
numBytes = pipeServer.Read(bytes, 0, BufferSize);
if (numBytes > 0)
{
int numChars = decoder.GetCharCount(bytes, 0, numBytes);
decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
msg.Append(chars, 0, numChars);
}
} while (numBytes > 0 && !pipeServer.IsMessageComplete);
decoder.Reset();
if (numBytes > 0)
{
owner.setTextbox(msg.ToString());//ownerInvoker.Invoke(msg.ToString());
}
} while (numBytes != 0);
pipeServer.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Client.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Diagnostics;
using System.Security.Principal;
namespace Client
{
public partial class Form1 : Form
{
public NamedPipeClientStream PipeStream;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe",
PipeDirection.Out,
PipeOptions.Asynchronous))
{
tbStatus.Text = "Attempting to connect to pipe...";
try
{
pipeClient.Connect(2000);
}
catch
{
MessageBox.Show("The Pipe server must be started in order to send data to it.");
return;
}
tbStatus.Text = "Connected to pipe.";
using (StreamWriter sw = new StreamWriter(pipeClient))
{
sw.WriteLine(textBox1.Text);
}
}
tbStatus.Text = "";
}
}
}
Wednesday, February 5, 2014
How to make font bold and italics?
Font a = new Font("Arial", 9, FontStyle.Bold | FontStyle.Italic);
How to read write XML files?
using System.Xml;
//##################### READ / WRITE #####################
private void ReadSettingsXML()
{
if (!System.IO.File.Exists(@".\DatFiles\Settings.xml"))
return;
XmlReader reader = XmlReader.Create(@".\DatFiles\Settings.xml");
try
{
while (reader.Read())
{
// Only detect start elements.
if (reader.IsStartElement())
{
// Get element name and switch on it.
switch (reader.Name)
{
case "locX":
if (reader.Read())
{
locX = Convert.ToInt32(reader.Value);
}
break;
case "locY":
if (reader.Read())
{
locY = Convert.ToInt32(reader.Value);
}
break;
}
}
}
reader.Close();
}
catch (Exception e)
{
MessageBox.Show(this, "ReadSettingsXML() " + e.Message, "Exception");
}
}
//************* WriteSettingsXML() *************
private void WriteSettingsXML()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = System.Text.Encoding.UTF8;
if (!System.IO.File.Exists(@".\DatFiles\Settings.xml"))
{
System.IO.Directory.CreateDirectory(@".\DatFiles\");
}
XmlWriter xmlw = XmlWriter.Create(@".\DatFiles\Settings.xml", settings);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("settings");
xmlw.WriteStartElement("locX");
xmlw.WriteValue(locX);
xmlw.WriteEndElement();
xmlw.WriteStartElement("locY");
xmlw.WriteValue(locY);
xmlw.WriteEndElement();
xmlw.WriteEndElement(); //Settings
xmlw.WriteEndDocument();
xmlw.Close();
}
//##################### READ / WRITE #####################
private void ReadSettingsXML()
{
if (!System.IO.File.Exists(@".\DatFiles\Settings.xml"))
return;
XmlReader reader = XmlReader.Create(@".\DatFiles\Settings.xml");
try
{
while (reader.Read())
{
// Only detect start elements.
if (reader.IsStartElement())
{
// Get element name and switch on it.
switch (reader.Name)
{
case "locX":
if (reader.Read())
{
locX = Convert.ToInt32(reader.Value);
}
break;
case "locY":
if (reader.Read())
{
locY = Convert.ToInt32(reader.Value);
}
break;
}
}
}
reader.Close();
}
catch (Exception e)
{
MessageBox.Show(this, "ReadSettingsXML() " + e.Message, "Exception");
}
}
//************* WriteSettingsXML() *************
private void WriteSettingsXML()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = System.Text.Encoding.UTF8;
if (!System.IO.File.Exists(@".\DatFiles\Settings.xml"))
{
System.IO.Directory.CreateDirectory(@".\DatFiles\");
}
XmlWriter xmlw = XmlWriter.Create(@".\DatFiles\Settings.xml", settings);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("settings");
xmlw.WriteStartElement("locX");
xmlw.WriteValue(locX);
xmlw.WriteEndElement();
xmlw.WriteStartElement("locY");
xmlw.WriteValue(locY);
xmlw.WriteEndElement();
xmlw.WriteEndElement(); //Settings
xmlw.WriteEndDocument();
xmlw.Close();
}
How to encrypt and decrypt files?
using System.Security.Cryptography;
namespace Form1
{
public partial class Form1 : Form
{
static readonly string PasswordHash = "abcdef";
static readonly string SaltKey = "S@LT&KEY";
static readonly string VIKey = "@afag214@#%afa";
//************* ReadProtectedInfo() *************
private bool ReadProtectedInfo()
{
try
{
if (!System.IO.File.Exists(@openFilePath))
{
return false;
}
char[] delimiterChars = { ' ', '\n', '\r' };
infoString = Decrypt(System.IO.File.ReadAllText(@openFilePath));
info = infoString.Split(delimiterChars);
return true;
}
catch (Exception e)
{
MessageBox.Show(this, "ReadProtectedInfo() " + e.Message, "Exception");
return false;
}
}
//************* WriteProtectedInfo() *************
private void WriteProtectedInfo()
{
if (!System.IO.File.Exists(@saveFilePath))
{
//System.IO.Directory.CreateDirectory(@".\DatFiles\");
var myFile = System.IO.File.Create(@saveFilePath);
myFile.Close();
}
string info = Encrypt(richTextBox1.Text);
System.IO.File.WriteAllText(@saveFilePath, info, Encoding.UTF8);
}
// ################### ENCRYPTION ###################
public static string Encrypt(string plainText)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
return Convert.ToBase64String(cipherTextBytes);
}
public static string Decrypt(string encryptedText)
{
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}
namespace Form1
{
public partial class Form1 : Form
{
static readonly string PasswordHash = "abcdef";
static readonly string SaltKey = "S@LT&KEY";
static readonly string VIKey = "@afag214@#%afa";
//************* ReadProtectedInfo() *************
private bool ReadProtectedInfo()
{
try
{
if (!System.IO.File.Exists(@openFilePath))
{
return false;
}
char[] delimiterChars = { ' ', '\n', '\r' };
infoString = Decrypt(System.IO.File.ReadAllText(@openFilePath));
info = infoString.Split(delimiterChars);
return true;
}
catch (Exception e)
{
MessageBox.Show(this, "ReadProtectedInfo() " + e.Message, "Exception");
return false;
}
}
//************* WriteProtectedInfo() *************
private void WriteProtectedInfo()
{
if (!System.IO.File.Exists(@saveFilePath))
{
//System.IO.Directory.CreateDirectory(@".\DatFiles\");
var myFile = System.IO.File.Create(@saveFilePath);
myFile.Close();
}
string info = Encrypt(richTextBox1.Text);
System.IO.File.WriteAllText(@saveFilePath, info, Encoding.UTF8);
}
// ################### ENCRYPTION ###################
public static string Encrypt(string plainText)
{
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
return Convert.ToBase64String(cipherTextBytes);
}
public static string Decrypt(string encryptedText)
{
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}
How to draw rounded rectangles / borders?
using System.Drawing.Drawing2D;
public void DrawRoundRect(Graphics g, Pen p, float X, float Y, float width, float height, float radius, bool fill, System.Drawing.Brush brush)
{
try
{
GraphicsPath gp = new GraphicsPath();
gp.AddLine(X + radius, Y, X + width - (radius * 2), Y);
gp.AddArc(X + width - (radius * 2), Y, radius * 2, radius * 2, 270, 90);
gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius * 2));
gp.AddArc(X + width - (radius * 2), Y + height - (radius * 2), radius * 2, radius * 2, 0, 90);
gp.AddLine(X + width - (radius * 2), Y + height, X + radius, Y + height);
gp.AddArc(X, Y + height - (radius * 2), radius * 2, radius * 2, 90, 90);
gp.AddLine(X, Y + height - (radius * 2), X, Y + radius);
gp.AddArc(X, Y, radius * 2, radius * 2, 180, 90);
gp.CloseFigure();
if (fill)
g.FillPath(brush, gp);
g.DrawPath(p, gp);
gp.Dispose();
}
catch (Exception ee)
{
MessageBox.Show(this, "DrawRoundRect" + ee.Message, "Exception");
}
}
private void backPanel_Paint(object sender, PaintEventArgs e)
{
Graphics v = e.Graphics;
v.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Pen pathPen = new Pen(Color.Black, 1);
DrawRoundRect(v, pathPen, backPanel.Left - 2, backPanel.Top - 2, backPanel.Width - 2, backPanel.Height - 2, 6, false, null);
base.OnPaint(e);
}
public void DrawRoundRect(Graphics g, Pen p, float X, float Y, float width, float height, float radius, bool fill, System.Drawing.Brush brush)
{
try
{
GraphicsPath gp = new GraphicsPath();
gp.AddLine(X + radius, Y, X + width - (radius * 2), Y);
gp.AddArc(X + width - (radius * 2), Y, radius * 2, radius * 2, 270, 90);
gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius * 2));
gp.AddArc(X + width - (radius * 2), Y + height - (radius * 2), radius * 2, radius * 2, 0, 90);
gp.AddLine(X + width - (radius * 2), Y + height, X + radius, Y + height);
gp.AddArc(X, Y + height - (radius * 2), radius * 2, radius * 2, 90, 90);
gp.AddLine(X, Y + height - (radius * 2), X, Y + radius);
gp.AddArc(X, Y, radius * 2, radius * 2, 180, 90);
gp.CloseFigure();
if (fill)
g.FillPath(brush, gp);
g.DrawPath(p, gp);
gp.Dispose();
}
catch (Exception ee)
{
MessageBox.Show(this, "DrawRoundRect" + ee.Message, "Exception");
}
}
private void backPanel_Paint(object sender, PaintEventArgs e)
{
Graphics v = e.Graphics;
v.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Pen pathPen = new Pen(Color.Black, 1);
DrawRoundRect(v, pathPen, backPanel.Left - 2, backPanel.Top - 2, backPanel.Width - 2, backPanel.Height - 2, 6, false, null);
base.OnPaint(e);
}
How to have custom font?
using System.Drawing;
using System.Runtime.InteropServices;
namespace Form1
{
public partial class Form1 : Form
{
//Add Font
[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);
FontFamily ff;
Font font;
}
private void Form1_Load(object sender, EventArgs e)
{
LoadFont();
this.Font = new Font(ff, 15f, FontStyle.Regular);
}
private void LoadFont()
{
try
{
byte[] fontArray = GPnL.Properties.Resources.helveticaneuewebfont;
int dataLength = GPnL.Properties.Resources.helveticaneuewebfont.Length;
IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
Marshal.Copy(fontArray, 0, ptrData, dataLength);
uint cFonts = 0;
AddFontMemResourceEx(ptrData, (uint)fontArray.Length, IntPtr.Zero, ref cFonts);
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddMemoryFont(ptrData, dataLength);
Marshal.FreeCoTaskMem(ptrData);
ff = pfc.Families[0];
font = new Font(ff, 15f, FontStyle.Regular);
}
catch (Exception e)
{
MessageBox.Show(this, "loadFont" + e.Message, "Exception");
}
}
using System.Runtime.InteropServices;
namespace Form1
{
public partial class Form1 : Form
{
//Add Font
[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);
FontFamily ff;
Font font;
}
private void Form1_Load(object sender, EventArgs e)
{
LoadFont();
this.Font = new Font(ff, 15f, FontStyle.Regular);
}
private void LoadFont()
{
try
{
byte[] fontArray = GPnL.Properties.Resources.helveticaneuewebfont;
int dataLength = GPnL.Properties.Resources.helveticaneuewebfont.Length;
IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
Marshal.Copy(fontArray, 0, ptrData, dataLength);
uint cFonts = 0;
AddFontMemResourceEx(ptrData, (uint)fontArray.Length, IntPtr.Zero, ref cFonts);
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddMemoryFont(ptrData, dataLength);
Marshal.FreeCoTaskMem(ptrData);
ff = pfc.Families[0];
font = new Font(ff, 15f, FontStyle.Regular);
}
catch (Exception e)
{
MessageBox.Show(this, "loadFont" + e.Message, "Exception");
}
}
How create rounded corner form?
namespace Form1
{
public partial class Form1 : Form
{
//Cut Border
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
int nLeftRect, // x-coordinate of upper-left corner
int nTopRect, // y-coordinate of upper-left corner
int nRightRect, // x-coordinate of lower-right corner
int nBottomRect, // y-coordinate of lower-right corner
int nWidthEllipse, // height of ellipse
int nHeightEllipse // width of ellipse
);
}
public Form1()
{
InitializeComponent();
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
private void Form1_Resize(object sender, EventArgs e)
{
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 15, 15));
}
{
public partial class Form1 : Form
{
//Cut Border
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
int nLeftRect, // x-coordinate of upper-left corner
int nTopRect, // y-coordinate of upper-left corner
int nRightRect, // x-coordinate of lower-right corner
int nBottomRect, // y-coordinate of lower-right corner
int nWidthEllipse, // height of ellipse
int nHeightEllipse // width of ellipse
);
}
public Form1()
{
InitializeComponent();
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
private void Form1_Resize(object sender, EventArgs e)
{
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 15, 15));
}
How to make font resize automatically based on label size?
private void Form1_Resize(object sender, EventArgs e)
{
pixels = Math.Min(label1.Height, label1.Width/2.8);
float fontSize = (float)(pixels * 0.8 * 72.0 / 96.0); //this is the magic
this.Font = new Font("Arial", fontSize, FontStyle.Bold);
}
{
pixels = Math.Min(label1.Height, label1.Width/2.8);
float fontSize = (float)(pixels * 0.8 * 72.0 / 96.0); //this is the magic
this.Font = new Font("Arial", fontSize, FontStyle.Bold);
}
How to move borderless forms?
using System.Runtime.InteropServices; //For "DllImportAttribute"
namespace Form1
{
public partial class Form1: Form
{
//To move Form
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
//Move Form
private void instLabel_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
namespace Form1
{
public partial class Form1: Form
{
//To move Form
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
//Move Form
private void instLabel_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
How to resize borderless forms?
Change form's padding to 3,3,3,3 to leave a space for the mouse to click and drag
//resize form
protected override void WndProc(ref Message m)
{
const UInt32 WM_NCHITTEST = 0x0084;
const UInt32 WM_MOUSEMOVE = 0x0200;
const UInt32 HTLEFT = 10;
const UInt32 HTRIGHT = 11;
const UInt32 HTBOTTOMRIGHT = 17;
const UInt32 HTBOTTOM = 15;
const UInt32 HTBOTTOMLEFT = 16;
const UInt32 HTTOP = 12;
const UInt32 HTTOPLEFT = 13;
const UInt32 HTTOPRIGHT = 14;
const int RESIZE_HANDLE_SIZE = 10;
bool handled = false;
if (m.Msg == WM_NCHITTEST || m.Msg == WM_MOUSEMOVE)
{
Size formSize = this.Size;
Point screenPoint = new Point(m.LParam.ToInt32());
Point clientPoint = this.PointToClient(screenPoint);
Dictionary<UInt32, Rectangle> boxes = new Dictionary<UInt32, Rectangle>() {
{HTBOTTOMLEFT, new Rectangle(0, formSize.Height - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
{HTBOTTOM, new Rectangle(RESIZE_HANDLE_SIZE, formSize.Height - RESIZE_HANDLE_SIZE, formSize.Width - 2*RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
{HTBOTTOMRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, formSize.Height - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
{HTRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, formSize.Height - 2*RESIZE_HANDLE_SIZE)},
{HTTOPRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, 0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
{HTTOP, new Rectangle(RESIZE_HANDLE_SIZE, 0, formSize.Width - 2*RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
{HTTOPLEFT, new Rectangle(0, 0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
{HTLEFT, new Rectangle(0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, formSize.Height - 2*RESIZE_HANDLE_SIZE) }
};
foreach (KeyValuePair<UInt32, Rectangle> hitBox in boxes)
{
if (hitBox.Value.Contains(clientPoint))
{
m.Result = (IntPtr)hitBox.Key;
handled = true;
break;
}
}
}
if (!handled)
base.WndProc(ref m);
}
//resize form
protected override void WndProc(ref Message m)
{
const UInt32 WM_NCHITTEST = 0x0084;
const UInt32 WM_MOUSEMOVE = 0x0200;
const UInt32 HTLEFT = 10;
const UInt32 HTRIGHT = 11;
const UInt32 HTBOTTOMRIGHT = 17;
const UInt32 HTBOTTOM = 15;
const UInt32 HTBOTTOMLEFT = 16;
const UInt32 HTTOP = 12;
const UInt32 HTTOPLEFT = 13;
const UInt32 HTTOPRIGHT = 14;
const int RESIZE_HANDLE_SIZE = 10;
bool handled = false;
if (m.Msg == WM_NCHITTEST || m.Msg == WM_MOUSEMOVE)
{
Size formSize = this.Size;
Point screenPoint = new Point(m.LParam.ToInt32());
Point clientPoint = this.PointToClient(screenPoint);
Dictionary<UInt32, Rectangle> boxes = new Dictionary<UInt32, Rectangle>() {
{HTBOTTOMLEFT, new Rectangle(0, formSize.Height - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
{HTBOTTOM, new Rectangle(RESIZE_HANDLE_SIZE, formSize.Height - RESIZE_HANDLE_SIZE, formSize.Width - 2*RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
{HTBOTTOMRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, formSize.Height - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE)},
{HTRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, formSize.Height - 2*RESIZE_HANDLE_SIZE)},
{HTTOPRIGHT, new Rectangle(formSize.Width - RESIZE_HANDLE_SIZE, 0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
{HTTOP, new Rectangle(RESIZE_HANDLE_SIZE, 0, formSize.Width - 2*RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
{HTTOPLEFT, new Rectangle(0, 0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE) },
{HTLEFT, new Rectangle(0, RESIZE_HANDLE_SIZE, RESIZE_HANDLE_SIZE, formSize.Height - 2*RESIZE_HANDLE_SIZE) }
};
foreach (KeyValuePair<UInt32, Rectangle> hitBox in boxes)
{
if (hitBox.Value.Contains(clientPoint))
{
m.Result = (IntPtr)hitBox.Key;
handled = true;
break;
}
}
}
if (!handled)
base.WndProc(ref m);
}
Subscribe to:
Comments (Atom)