JG Vimalan's Blog

It is all about coding!

Handling windows of other processes

In this post, I am going to explain bringing a minimized window of other process to normal state.  Inorder to do that, you need to use the ‘showwindow’ api from win32. The detailed code is given below,

[DllImport(“user32.dll”)]
        private static extern int ShowWindow(int hwnd, int nCmdShow);

implement the ShowWindow in a method.

                 try
                {                   
                    System.Diagnostics.Process[] mygameProcess = System.Diagnostics.Process.GetProcessesByName(“mygame”);
                    if (mygameProcess.Length > 0)
                    {
                        System.Diagnostics.Process proc = mygameProcess[0];                       
                        TvStarter.ShowWindow(proc.MainWindowHandle.ToInt32(), 1); //TvStarter is class name                        
                    }                   
                }
                catch
                {
                    //log exception
                }

this is very useful when you create an application which controls several other related applications in .Net.

November 26, 2010 Posted by | C#.NET | Leave a comment

Auto start .NET application on system reboot

Inorder to start you .net application whenever system starts, you need to set the application path in the registry. In registry, there is a special location called ‘Run’ under SOFTWARE\Microsoft\Windows\CurrentVersion\. You need to make an entry in the ‘Run’ key for starting your application on every reboot.

The following code snippet will give a quick idea on setting entry in the ‘Run’ key,

internal void SetStartUp()
        {
            System.IO.Directory.SetCurrentDirectory(
                System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            string path = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location) + “\\mygametray.exe“;       

            var rkApp = Registry.LocalMachine.OpenSubKey(@”SOFTWARE\Microsoft\Windows\CurrentVersion\Run”, true);
            if (rkApp.GetValue(“mygametray”) == null)
            {
                rkApp.SetValue(“mygametray “, ‘”‘ + path + ‘”‘);
            }
            rkApp.Close();
        }

You need to perform this action while performing installation.

November 26, 2010 Posted by | C#.NET | Leave a comment

Passing parameter to .NET application from registry

I got a task where my .net application starts at reboot. It expects a parameter to perform certain actions while starting. So, inorder to pass parameter from the registry, I made an entry as shown below in the Run key under HKEY_LOCAL_MACHINE

“C:\Users\JGVimalan\mygames\mygametray.exe” %1

this ‘1’ will be passed as a parameter to the .net application.

November 26, 2010 Posted by | C#.NET | Leave a comment

Auto scroll button text on focus in WPF

There may be situations where you need to set button text dynamically.  The button text may be lengthier than expected and full text may not be visible. At this point, one of the best option is to auto scroll the text when user places the mouse on the button. Here is the code sample on how I did that in my wpf application.

XAML

<Window x:Class=”WpfApp.Window1″
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
    Title=”Window1″ Width=”500″ Height=”100″>
    <Grid>
        <Grid x:Name=”grdButton” Margin=”0,0,47,0″ >
            <Grid>
                <Rectangle
                    VerticalAlignment=”Stretch”
                    Stroke=”#FFCCCCCC”
                    StrokeLineJoin=”Round”
                    StrokeThickness=”2″
                    RadiusX=”10″
                    RadiusY=”10″
                    Margin=”6″ />

                <Grid x:Name=”grdFocus”>
                    <Grid.RowDefinitions>
                        <RowDefinition Height=”0.46*”/>
                        <RowDefinition Height=”0.54*”/>
                    </Grid.RowDefinitions>

                    <Rectangle Grid.RowSpan=”2″
                               Margin=”-5″
                               RadiusX=”12″
                               RadiusY=”12″
                               StrokeThickness=”0″>
                        <Rectangle.Fill>
                            <SolidColorBrush Opacity=”0.2″ Color=”DarkBlue”/>
                        </Rectangle.Fill>
                    </Rectangle>
                    <Rectangle x:Name=”recFocus” RadiusX=”12″ RadiusY=”12″ Grid.RowSpan=”2″>
                        <Rectangle.Fill>
                            <LinearGradientBrush StartPoint=”0.682896,1.05319″ EndPoint=”0.682896,0.0212779″>
                                <GradientStop Color=”DarkBlue” Offset=”0″/>
                                <GradientStop Color=”DarkBlue” Offset=”0.561″/>
                                <GradientStop Color=”#FFFFA300″ Offset=”1″/>
                                <GradientStop Color=”#FFFF801F” Offset=”0.235″/>
                            </LinearGradientBrush>
                        </Rectangle.Fill>
                    </Rectangle>

                    <Path Fill=”White” Stretch=”Fill” Opacity=”0.229995995759964″ Data=”F1 M709.168,234.827 L95.5,234.827 95.5,215.83225 C95.5,205.98525 100.70132,201.5 108.52932,201.5 L697.4544,201.82573 C705.2794,201.82573 709.50651,208.26538 709.50651,218.11238 z” Margin=”2″/>

                </Grid>

                <Label x:Name=”lblMessageText” Content=”This is a wpf application. This sample text will scroll automatically on mover hover.”   Foreground=”White” FontWeight=”Bold”
                       VerticalAlignment=”Center” FontSize=”18″ HorizontalAlignment=”Left” Margin=”10,0,0,0″ Width=”465″/>                       

                <Button x:Name=”btnOption” Opacity=”0″ Cursor=”Hand” MouseEnter=”btnOption_MouseEnter” 
           MouseLeave=”btnOption_MouseLeave” GotFocus=”btnOption_GotFocus” LostFocus=”btnOption_LostFocus”/>
            </Grid>
        </Grid>       
    </Grid>
</Window>

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApp
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private DispatcherTimer timer;
        private int _textScrollLength = 28;
        private string _displayText = string.Empty;

        public Window1()
        {
            InitializeComponent();
            _displayText = lblMessageText.Content.ToString();
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            timer.Tick += new EventHandler(timer_Tick);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (lblMessageText.Content.ToString().Length == 0)
                    lblMessageText.Content = ”                                                  ” + _displayText;
                else
                    lblMessageText.Content = lblMessageText.Content.ToString().Substring(1);
            }
            catch { }
        }

        private void BtnGotFocus()
        {
            try
            {
                grdFocus.Visibility = Visibility.Visible;
              
                if (!string.IsNullOrEmpty(_displayText))
                {
                    if (_displayText.Length > _textScrollLength)
                    {
                        if (timer != null)
                        {
                            timer.Start();
                        }
                    }
                }
            }
            catch { }
        }

        private void BtnLostFocus()
        {
            try
            {               
                if (timer.IsEnabled)
                {
                    lblMessageText.Content = _displayText;
                    timer.Stop();
                }
            }
            catch { }
        }

        private void btnOption_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            BtnGotFocus();
        }

        private void btnOption_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            BtnLostFocus();
        }

        private void btnOption_GotFocus(object sender, RoutedEventArgs e)
        {
            BtnGotFocus();
        }

        private void btnOption_LostFocus(object sender, RoutedEventArgs e)
        {
            BtnLostFocus();
        }
    }
}

Output:

The complete source code is available for download at http://cid-670f5e7529eed46d.office.live.com/self.aspx/.Public/WPF/WpfApp.zip

November 23, 2010 Posted by | XAML | Leave a comment

The calling thread cannot access this object because a different thread owns it.

I got this error message when I was implementing BackgroundWorker in my WPF application. This error message got caught when I tried to access a dropdownlist value in the ‘DoWork’ event of worker process. So, instead of accesing the controls directly in ‘DoWork’ event, I passed the necessary values as arguments in the RunWorkerAsync method. Invoking the RunWorkerAsync method calls the ‘DoWork’ event. So, the result code is as follows,

object[] args = new object[3];
            args[0] = cmbGender.SelectedValue;
            args[1] = cmbState.SelectedValue;
            args[2] = cmbCountry.SelectedValue;
                       
            if (!bgWorker.IsBusy)
                bgWorker.RunWorkerAsync(args);

and, in the ‘DoWork’ method, I will get the parametes and use them as shown below,

void bgWorker_DoWork(object sender, DoWorkEventArgs e
{
 var args = e.Argument as object[];
if (Convert.ToInt32(args[2]) != 0)
{

this will solve the issue.

November 19, 2010 Posted by | C#.NET | 9 Comments

Set hotkey for buttons in XAML application at runtime

I got a task where I need to set hotkeys for the buttons generated based on the records displayed in a grid. Each record displayed in the grid will have a button. The first record which have a button whose shortcut key will be “shift 0”.  Similarly, for every records displayed, a button will be  created whose hotkey will be “shift 1, shift 2… upto shift 9 respectively. So, when the user presses shift 1, the corresponding button’s click event will be invoked. To achieve this, follow the steps given below,

a. Add a string array as shown below in your application. Here, I am using a XAML application for performing this example.

string[] appShiftKey = new string[10] { “)”, “!”, “@”, “#”, “$”, “%”, “?”, “&”, “*”, “(” };

These symbols are available in the keyboard and they were ordered to represent the numbers 0,1, 2, 3..  9 in the keyborad.

b. In the XAML button control, use the content property to set the hotkey.

public string myButtonHotKey
        {
            get { return submitButton.Content.ToString(); }
            set { submitButton.Content = value; }
        }

c. In the code, set the hotkey while iterating throught the records. Limit the record display to 10 in the grid to achieve this fuctionality.

myButtonHotKey = string.Format(“_{0}”, appController.appShiftKey[itemIndex])}

d. The outcome will be as follows, when you click the respective hotkeys, the buttons click event will fire and you can perform desired acition in that event.

November 14, 2010 Posted by | XAML | Leave a comment