Pages

Monday, April 19, 2010

Its Time to Celebrate

After a long await, its now time to celebrate. There are two reasons of this.

1. Launch of Visual Studio 2010 


Its a long wait for this lovely IDE. The Visual Studio 2010 is a truly WPF IDE produced by Microsoft which I believe is much more enhanced and powerful than the previous ide's. Apart from IDE features, the IDE extensions can be built very easily with superior framework support with it. Even deployment of Extension is also very easy. I have built one extension for this IDE which you can get from :
http://www.codeproject.com/KB/miscctrl/InfoBox_VSX.aspx


You can also check whats new in the IDE from :
http://msdn.microsoft.com/en-us/library/bb386063%28v=VS.100%29.aspx

To download the trial version you can get it from :
http://msdn.microsoft.com/hi-in/subscriptions/default(en-us).aspx

2. Anniversary of DotNetFunda.com

I have been participating in this site for the last few months, and I think its another lovely place where you can share your own knowledge. This time sharing your knowledge gives you a chance of wining lovely gifts.



Dont think I am advertising this in my blog. Actually I would love if some of you win few things from here.

Thank you . And Cheers.. on this lovely note.

Tuesday, April 13, 2010

Pack URI to Reference Component

WPF comes with a new URI Scheme which one can use to reference a file that is packaged as resource into the assembly. Rather than using DynamicResource, or specifying the absolute path for the Resource (which would eventually translate itself to relative reference always), the actual path can also be restored using pack:\\ URI Schema.

Usage 

Pack Uri entails the Open Packaging Convension which determines organization and identification of Resources. Let us look into this in detail using few examples :

1. pack://application:,,,/ResourceFile.xaml

Here the application will find the file named ResourceFile.xaml directly to the Application Directory.  Thus to refer to any file located in current assembly and which is in Root folder, you might use this. 

2.  pack://application:,,,/Subfolder/ResourceFile.xaml

If the file is located within a subfolder, to refer to it, you need to use Relative path from the root directory. Here you can see there is a subfolder named Subfolder where the ResourceFile.xaml is stored.

3. pack://application:,,,/ReferencedAssembly;component/ResourceFile.xaml

If you want to refer to the resource using the Referenced dll, you might use this. Remember the ReferencedAssembly refers to the name of the Assembly. Also remember if you place the ResourceFile.xaml in your root directory of referencedAssembly you should specify the path using component/ResourceFile.xaml. Therefore you can see, every file that is referenced through the ReferencedAssembly should always be relative to component folder.  So for instance
pack://application:,,,/MyCustomdll;component/MyResource.xaml. 


4. pack://application:,,,/ReferencedAssembly;component/subfolder/ResourceFile.xaml

Similar to one specified above, if the resource is placed within a subfolder within the assembly, you need to again reference that relative to component folder.

5. pack://siteoforigin:,,,/Subfolder/ResourceFile.xaml

Finally if say your file is located to an assembly to which the current assembly is referenced to, you might use siteoforigin in this case to refer to a file located to the parent of this assembly.

Here you must remember that using this type of urls will make the dll tightly coupled with one another. Thus it will expect the dll which reference it to contain a file inside subfolder of its Resource tree structure.

Conclusion

It is really new to everybody to use these type of urls in WPF applications. Even I am also surprised to see such a new addition. But now I an using it, and also it works great to me. Try out them yourself, I hope you will find them interesting .

Thanks for reading.
Reference
For further reference you can read this Article

Monday, April 12, 2010

Screen Capture in WPF & WinForms Application

I was wondering how one can capture screenshot from an application. I saw many application was doing them. This thought made me interested to write an application that can take ScreenShot. In this article, I will demonstrate how one can take screenshot directly from the Desktop area using WinForms and WPF.


WinForms Application

In WinForms application, it is very easy to grab a screen snapshot. To do this you only need to create an object of Bitmap, on which you want to draw the image, get Graphics object from the Bitmap and then use CopyFromScreen method to actually draw the image into the Bitmap. To demonstrate let us consider this method :
public void CaptureScreen(double x, double y, double width, double height)
 {
            int ix, iy, iw, ih;
            ix = Convert.ToInt32(x);
            iy = Convert.ToInt32(y);
            iw = Convert.ToInt32(width);
            ih = Convert.ToInt32(height);
            Bitmap image = new Bitmap(iw, ih, 
                   System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(image);
            g.CopyFromScreen(ix, iy, ix, iy, 
                     new System.Drawing.Size(iw, ih), 
                     CopyPixelOperation.SourceCopy);
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.DefaultExt = "png";
            dlg.Filter = "Png Files|*.png";
            DialogResult res = dlg.ShowDialog();
            if (res == System.Windows.Forms.DialogResult.OK)
                image.Save(dlg.FileName, ImageFormat.Png);
 }

The above code takes Start X, Start Y, width and height and saves the image  into the disk. In this method, I created an object of Bitmap where I would be going to draw the image. There are large number of PixelFormat supported by the Bitmap object. You can choose anyone of them which suits you. As I am working on 32 Bit true color environment, I used Format32bppArgb.

After doing this, you need to actually draw into the Bitmap object. To do this, you need to get graphics object from the image. I used Graphics.FromImage(image) to grab the graphics object from the image, so that the graphics could draw into the Bitmap object.

Finally I called g.CopyFromScreen which actually captures the screen snapshot, just like what Screenshot does and writes on the Bitmap. The argument that I have passed determines the dimension of the image. The x, y, width and height determines where from the screen the snapshot should start and its width and height upto which it must go. At last, I used image.Save to save the image in Png format in the disk.

You should note, if you want transparency in your image, you should use PNG, as it supports transparency.


A little Depth


If you want to know what exactly happens in background, let us use DllImport to demonstrate the concept. Actually Screen capture is made using a API call to BitBlt. This method can be called with appropriate dimension just as the managed method CopyFromScreen, and get the image.
To implement using Native code :
internal class NativeMethods
{

    [DllImport("user32.dll")]
     public extern static IntPtr GetDesktopWindow();
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowDC(IntPtr hwnd);
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetForegroundWindow();
    [DllImport("gdi32.dll")]
    public static extern UInt64 BitBlt(IntPtr hDestDC, int x, int y, 
       int nWidth, int nHeight, IntPtr hSrcDC, 
       int xSrc, int ySrc, System.Int32 dwRop);

}

The NativeMethod BitBlt actually the most useful method in this context.  To grab the image using this you can use :
public void SaveScreen(double x, double y, double width, double height)
{
      int ix, iy, iw, ih;
      ix = Convert.ToInt32(x);
      iy = Convert.ToInt32(y);
      iw = Convert.ToInt32(width);
      ih = Convert.ToInt32(height);
      try
      {
          Bitmap myImage = new Bitmap(iw, ih);
          Graphics gr1 = Graphics.FromImage(myImage);
          IntPtr dc1 = gr1.GetHdc();
          IntPtr dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow());
         NativeMethods.BitBlt(dc1, ix, iy, iw, ih, dc2, ix, iy, 13369376);
         gr1.ReleaseHdc(dc1);
         SaveFileDialog dlg = new SaveFileDialog();
         dlg.DefaultExt = "png";
         dlg.Filter = "Png Files|*.png";
         DialogResult res = dlg.ShowDialog();
         if (res == System.Windows.Forms.DialogResult.OK)
             myImage.Save(dlg.FileName, ImageFormat.Png);
       }
       catch { }
 }

In this function, I am doing the same thing that I did for the earlier. The difference is that, here I ma using NativeMethod to invoke the BitBlt directly rather than using the Managed code CopyFromScreen method.

If you want to capture the whole working area, you can use
Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
Screen.PrimaryScreen.Bounds.Width, and
Screen.PrimaryScreen.Bounds.Height
as its arguments.

Sample Application

In this sample application, you will find a WPF application that allows you to capture a part of the screen. Lets look how it works :

1. Run the application, you will be provided with a screen where you can drag mouse to take screenshot.
2. After you drag the mouse and Release the mouse, you will see a dialog box to save the image.
3. Finally after you save, you will see the snapshot in png format.

Thus it is very easy to work with Screen capture.

I hope you will like this application.

Download the Sample Application - ScreenShotSample.Zip(50KB)

Sunday, April 11, 2010

Using SpellChecker in TextboxBase

WPF TextBox or RichTextBox or any control inherited from TextboxBase has an inbuilt support for Spellchecking functionality, which you might employ very easily just by enabling the SpellCheck menu for the Textbox. In this article I am going to discuss how you can easily invoke spellchecking functionality in your WPF application.

Basic Usage


WPF provides a new object called SpellCheck. This object can be applied to any TextBoxBase object and thereby the object will behave automatically with the spellcheck functionality. To do this, lets look at the example :
<stackpanel height="150" margin="50">
      <textblock text="Enter Content"></textblock>
      <textbox acceptsreturn="True" spellcheck.isenabled="True" x:name="txtBox">
</textbox></stackpanel>

In the above example, you can see the TextBox txtBox, have SpellChecker enabled. This ensures the textbox automatically detect misspelled words and will put an underline on the word. When you run the application, you will see the textbox to appear like this :
You can see all the misspelled word is shown with red underline. These words can easily be corrected by using the TextBox default ContextMenu. Right clicking on the word will give you a list of suggestions for the current word which you might choose to change the word in the paragraph.

SpellCheck.IsEnabled is actually a Dependency property. So you can easily use it to set in Style setters. You can also use global setter to apply SpellChecking to every control you put in the window very easily.

<style targettype="{x:Type TextBoxBase}" x:key="txtBasic">
<setter Property="SpellCheck.IsEnabled" Value="true" />
<setter Property="SpellCheck.SpellingReform" Value="PreAndPostreform" />
</style>

Now you can easily define any TextBox or RichTextBox or any control that derives TextboxBase and use the Style to apply SpellChecker. You can also use

<style basedon="{StaticResource txtBasic}" targettype="{x:Type TextBox}">
<style TargetType="{x:Type RichTextBox}" BasedOn="{StaticResource txtBasic}" />

By doing this, any TextBox or RichTextBox which you place in your Window will automatically have spellChecking enabled.
You can also enable/disable the SpellCheck from codebehind.
SpellCheck.SetIsEnabled(txtBox, true);
SpellCheck.SetSpellingReform(txtBox, SpellingReform.PreAndPostreform);

Spelling error can be detected based on the carat location. TextBoxBase contains a few methods that you can invoke to get Spelling errors. SpellingError is a class which provides the current Spelling error word with an enumerable of Suggessions.

READ THE FULL ARTICLE

Wednesday, April 7, 2010

ASP.NET Page Life Cycle Video

Hi Guys,

It is a good experience to put forward an online session on ASP.NET page life cycle. It is my first session, so it might seem to you like professional.

The Session includes how the basics on ASP.NET, how request comes to the server, how IIS receives the request and finds appropriate ISApiFilters associated with it, how HttpRuntime picks up a new object of HttpApplication and calls appropriate HttpHandlers; concepts on HttpHandlers, HttpModules and HttpPipeline, their usage etc.

In this final part of the session, I have discussed about the actual ASP.NET page life cycle, its events and their nature.

You can download the online session from
ASP.NET Page LifeCycle

If you find issues to run this video, please follow :
http://support.microsoft.com/kb/944586

I am really thankful to entire DotNetFunda & Questpond team for their support and helping me out with a successful video session.

Please provide your feedback.

Working with WebBrowser in WPF

WebBrowser is a very common control for any type of windows application where one needs to show html document. WPF provides a superior WebBrowser control which allows you to show, navigate and communicate html documents.

WPF introduces WebBrowser control to ensure that we can show html pages embedded inside the control. It is really very important to know how to use a WebBrowser as while working with WPF, if you want to show content from the server as HTML, or load an html document directly inside the WPF window, this control will be the only option to you. A WebBrowser control actually uses Internet Explorer Browser Engine internally, so you need it to be installed in the machine (which of course every machine installs by default ) before loading it inside the WPF control. So if you update the IE of your machine, the web browser will update as well.

In this article I will discuss the basic usage of WPF WebBrowser control, so that the use of this would come to you very easy.




 READ THE FULL ARTICLE

Monday, April 5, 2010

Article Selected @WindowsClient.net

It is always a great achievement to find my article in www.windowsclient.net. It happened again. This is For "Fun with Borders and Effects" .

I am really thankful to all of the members who liked my article, wanted me to write, especially Abhijit Jana, and Sheo Narayan.

Thank you all.

READ THE FULL ARTICLE