February 15, 2011

WPF Databinding to User Settings

Used this website as a reference: Binding to User Settings in WPF

In the Xaml add
xmlns:Properties="clr-namespace:XXX.Properties"
to the window/control attributes section where XXX is the application namespace under which the properties are defined

Then to bind a setting
Text="{Binding Source={x:Static Properties:Settings.Default}, Path=SomeSetting, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

Note without the 'UpdateSourceTrigger' definition the updating did not work when the update was made programmatically. By default the 'UpdateSourceTrigger' is set to 'FocusChanged' so that only when the control lost it's focus would the change be passed on back to the source.
Why this change worked

Weak References

See here for MSDN Description
And here is sample usage
Here is a Tutorial on using Weak References

"Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection."
"Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects."

February 10, 2011

WPF Accessing a resource based control created through Xaml

Here is Xaml:
<Window x:Class="DevHelperWpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Development Helper" Height="300" Width="300" ShowInTaskbar="False" 
    WindowState="Minimized" WindowStartupLocation="CenterScreen" Icon="/DevHelperWpf;component/AppIcon.ico" ResizeMode="CanResize" Loaded="Window_Loaded">
    <Window.Resources>        
     <ContextMenu x:Key="NotifierContextMenu" Placement="MousePoint">
            <MenuItem Name="menuEmptyTemp" Header="_Empty Temp" Click="Menu_EmptyTemp" ToolTip="Clean out your Temp directory" />
            <MenuItem Name="menuSaveImage" Header="Save _Clipboard Image To File" Click="Menu_ClipboardToFile" ToolTip="Save an image to the clipboard" />
            <MenuItem Name="menuP4QCC" Header="P4QCC" Click="Menu_P4QCC" ToolTip="Start P4QCC utility" />
....
Now accessing the control through a method on the parent window (note this is the 'Window1' instance):
contextMenu = (ContextMenu)this.FindResource("NotifierContextMenu");
    
MenuItem item = new MenuItem();
foreach (MenuItem mi in contextMenu.Items)
{
  ...
}

February 8, 2011

Finding CommandLines of Other Processes

Add a reference to "System.Management" assembly
using System.Management;
...

static void FindAllProcessNameWithCommandLine()
{
    string wmiQuery = "Select * from Win32_Process";
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
    ManagementObjectCollection retObjectCollection = searcher.Get();
    foreach (ManagementObject retObject in retObjectCollection)
    {
        string exename = retObject["Name"] as string;
        string commandline = retObject["CommandLine"] as string;
        Debug.WriteLine(exename + ": \'" + commandline + "\'");
    }
}

Sample Output:
...
procexp64.exe: '"C:\Program Files (x86)\Tools\ProcessExplorer\procexp.exe" '
explorer.exe: '"C:\Windows\explorer.exe" /n,/select,"C:\Users\RBovilll\AppData\Local\Temp\Kabo.zip"'
SMSCliUI.exe: 'C:\Windows\SysWOW64\CCM\SMSCliUI.exe -Embedding'
devenv.exe: '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe" '
splwow64.exe: 'splwow64'
...

January 27, 2011

C++ Declaring A Static Type


In header
class Xxx {
...
  static sometype dict_;
...
In source:
sometype Xxx::dict_;

Windows Message Queues Important Notes

About Messages and Message Queues
PeekMessage
Win32 Message Processing Primer
See also this post on this blog

PostMessage => Asynchronous, message goes into the message queue
SendMessage => Synchronous, message is sent to WinProc immediately and processed immediately.
Note: WM_PAINT, WM_TIMER, WM_QUIT handled differently when posted. They are only processed when there are no other messages in the queue. Multiple WM_PAINT messages for the same window are combined consolidating all invalid parts of the client area into a single area.
GetMessage() - Does not return until message matching the filter criteria is found. Removes message from queue
while (GetMessage (&msg, NULL, 0, 0))
{
  TranslateMessage (&msg) ;
  DispatchMessage (&msg) ;
}
PeekMessage() - Looks for message matching the filter criteria. Returns immediately. Whether the matching message is removed from the queue or not is determined by the last parameter of the method
do
{
  if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
  {
    TranslateMessage (&msg) ;
    DispatchMessage (&msg) ;
  }
} while (msg.message != WM_QUIT);
Neither GetMessage or PeekMessage will remove WM_PAINT messages unless the update area of the message is null!
 

January 12, 2011

Simple Pie Chart using WPF Toolkit

Here is more detail
Also look at WPF Toolkit Tutorial – Part 1

A simple pie chart example in that there only 2 wedges in the pie chart!
Add a reference to the WPFToolkit data visualisation assembly ("...\Program Files\WPF Toolkit\v3.5.50211.1\System.Windows.Controls.DataVisualization.Toolkit.dll")

Add following xaml to the window where the pie chart will be placed:
<Window ...
  <!-- First define the namespace for charting -->
  xmlns:charting="clr-namespace:
  System.Windows.Controls.DataVisualization.Charting;
  assembly=System.Windows.Controls.DataVisualization.Toolkit"

  <charting:Chart Name="pieChart">
    <charting:PieSeries ItemsSource="{Binding}" 
      IndependentValueBinding="{Binding Path=Description}"
   DependentValueBinding="{Binding Path=Percentage}"
    />
  </charting:Chart>
Set the Pie chart wedges
void AssignPieChartWedges()
{
    System.IO.DriveInfo cdrive = new System.IO.DriveInfo("C");
    double availPercentage = Math.Round(100.0d * 
        (double)cdrive.TotalFreeSpace / (double)cdrive.TotalSize);

    List<DrivePercentage> dpList = new List<DrivePercentage>();
    dpList.Add(new DrivePercentage() 
    { Percentage=availPercentage, Description="Free" });
    dpList.Add(new DrivePercentage() 
    { Percentage=100.0d-availPercentage, Description="Used" });
    pieChart.DataContext = dpList;
}