Jul 26, 2012

[How to] Convert Dictionary.Keys (or Values) to Array

For example, there's a dictionary like this,


using System.Collections.Generic;


Dictionary<string, int> dict = new Dictionary<string, int>();


Now we want to retrieve all keys,


var keys = dict.Keys;


That is. However, the keys is another collection type an we want to convert it to array.
There was an old way -- CopyTo.


string[] keyArray = new string[dict.Count];
dict.Keys.CopyTo(keyArray, 0);


If you have looking for better solution, and you're using C# 3.0 (and above).
Congratulation! According the MSDN library, there's a directly way -- ToArray

May 23, 2012

[How to] Single Instance of Application

This article is NOT talking about Singleton Pattern, 
which is a design pattern that keep a class have only one instance.
We're going to make an application have only one instance in the OS.


In VB.Net, you just need to open project property page and check "Single Instance".
However, there's no this option in C#.


We may observe some VB.Net auto generated codes, such as "Application.Designer.vb",
and we'll find out that there're some codes like these:


Public Sub New()
  MyBase.New(AuthenticationMode.Windows)
  Me.IsSingleInstance = true
  Me.EnableVisualStyles = true
  Me.SaveMySettingsOnExit = true
  Me.ShutDownStyle = ShutdownMode.AfterMainFormCloses
End Sub


That is. We just need to rewrite it according C#'s style.

May 14, 2012

[Troubleshooting] User Control Overrides Color does not Auto-Generate Codes

Problem symptom:

When you make a class that inherits Control or UserControl, and you want to overrides ForeColor or BackColor.
For example, you may want to use a brush to instead of color.

using System.Drawing;

public MyControl : Control
{
  private Brush _fBrush = new SolidBrush(Color.Navy);
  
  public overrides Color ForeColor()
  {
    get { return _fBrush.Color; }
    set
    {
      _fBrush.Color = value;
      this.Refresh();
    }
  }
}

It looks to make sense. 
However, when you use "MyControl" in your application and change the ForeColor property to Color.Red in design mode, it might not generate the corresponding code in InitializeComponent() method.

Solution:

May 4, 2012

[How to] Transfer Pointer to C/C++ DLLs

In "SomeDLL.dll", there's an entry point "GetValue" which declared as
int GetValue(char* buffer, int length)


We should import it in C# first.
[DllImport("SomeDLL.dll")]
public static extern int GetValue(IntPtr buffer, int length);


Therefore, how to use it?

Feb 21, 2012

[Tips] ?: Operator and ?? Operator

Use "if" condition:
if (condition)
  result = t;
else
  result = f;

if (obj != null)
  result = obj;
else
  result = something;


Use "?:" operator
result = condition ? t : f;


Use "??" operator
result = obj ?? something;

Feb 20, 2012

[How to] Memory Allocate

If we want to dynamic allocate N bytes of memory.
And then, reallocate it to X bytes. After all, release it.


In the case of C/C++:
char* bp = malloc(sizeof(char) * N);
bp = realloc(bp, sizeof(char) * X);
free(bp);


Feb 9, 2012

[How to] Color of A Point on The Screen

using System.Drawing;
using System.Drawing.Drawing2D;

Bitmap bitmap = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bitmap);


Give a point that you want
g.CopyFromScreen(this.Location, new Point(0, 0), new Size(1, 1));


This is what you needed
Color result = bitmap.GetPixel(0, 0);

Jan 17, 2012

[How to] Refresh UI in Threads (Delegate)

private delegate void Updater(Control ctrl);


private void Update(Control ctrl)
{
    if (this.InvokeRequired)
    {
        Updater u = new Updater(Update);
        this.Invoke(u, ctrl);
    }
    else
    {
        ctrl.Refresh();
    }
}


And call this method in threads
this.Update(this);

Jan 10, 2012

[How to] Change Task of Thread (Delegate)

using System.Threading;

Action task;

void task1() { }
void task2() { }
void task3() { }

void doTask(){
    while (true)
        task();
}

Thread thread = new Thread(doTask);
task = task1;
thread.Start();

Switch to task2
task = task2;


Switch to task3
task = task3;


And so on.

Jan 9, 2012

[How to] Function Array (Delegate)

using System;


case: void funcs(void)
Action[] func = {func1, func2, func3, ...};


case: void funcs(int)
Action<int> func = {func1, func2, func3, ...};


case: bool funcs(void)
Func<bool> func = {func1, func2, func3, ...};


Refer to all of the overloaded constructor of Action and Func.

[How to] Load Class From Assembly

using System.Reflection;

Assembly asm = Assembly.LoadFrom("file.dll");
Type type = asm.GetType("namespace.classpath");

object obj = Activator.CreateInstance(type);


Or
object obj = Activator.CreateInstance(type, new object[] {param1, param2, param3, ...});


Do any casting if needed.