Thursday, July 19, 2012

Limit flickering on winforms

Here's the snippet to limit flicker in forms. Put it above the initialize component method in your constructor.
Code:
//limit flicker  
SetStyle(ControlStyles.OptimizedDoubleBuffer   
    | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);  
 InitializeComponent();  
Cheers! Source: mijalko

Monday, July 16, 2012

Process memory usage percentage not computing properly

In a scenario when i want to compute the percentage of a process memory consumption against the total memory installed, I encountered a logic error where in the result is zero. The simple formula is this:
Code:
double x = p.PrivateMemorySize64 / installed_memory_pc * 100; 

However, the result in x is zero. The trick is to convert p.PrivateMemorySize64 and installed_memory_pc to megabytes by dividing each variable with 1048576. 1Mb = 1048576 bytes. The modified formula is:
Code:
mbInstalledMemory = (int)installedMemory / 1048576;  
mbUsage = (int)p.PrivateMemorySize64 / 1048576;
Then you can apply the percentage formula.
Cheers!

Wednesday, July 4, 2012

Enable/Disable ToolstripButton using Delegates (Thread)

Assuming you will access the toolstrip button from another thread, then here's the code to do it.
Code:
  delegate void EnableDisableButtonRunDeleg(bool value);  
      private void EnableDisableButtonRun(bool value)  
      {  
        if (tsMenu.InvokeRequired)  
        {  
         this.tsMenu.Invoke(new EnableDisableButtonRunDeleg   
          (EnableDisableButtonRun), value);  
        }  
        else  
        {  
          ToolStripItem ts = tsMenu.Items[0];  
          ((ToolStripButton)ts).Enabled = value;  
        }  
      }

Cheers!

Monday, July 2, 2012

Get Icon from process (C#)

Code:
Icon ico = Icon.ExtractAssociatedIcon(process.MainModule.FileName);
if you want to convert to image, just cast it to a bitmap object.
Source: Stack overflow

Prevent Listview column from being resized (Winform)

I added the snippet below in the columnwidthchanging event:
Code:
  switch (e.ColumnIndex)  
        {  
          case 0:  
            e.NewWidth = 400;  
            break;  
          case 1:  
            e.NewWidth = 200;  
            break;  
          case 2:  
            e.NewWidth = 100;  
            break;  
          case 3:  
            e.NewWidth = 100;  
            break;  
          default:  
            break;  
        }  
       e.Cancel = true;

Where 400, 200, and 100 are the original column sizes.