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?