Category Archives: WPF

Članci koji se odnose na WPF

XAML Peak new feature in Visual Studio 2015


The latest version of the Visual Studio 2015 is bringing a lot of new features for WPF and XAML programming language. For this blog post I would like to share the XAML Peak Definition. Peak Definition is not new, the current version of Visual Studio 2013 supports peak definition only for C# and VB. Now we have the same functionality within XAML. Event more, in the Visual Studio 2015 peak definition is working in mixed mode, so you can reach any definition regladless of the programming languges (C#, VB or XAML).

XAML peak allows you to get definition or content of any name defined in the XAML code. For example lets see the following XAML code. Right click on the MainWindow class and choose “Peak Definition”:

peakxamlsl1

After the command is selected, the new inline window appears within xaml, and the user can easily see or change the code behind selected definition. Peak Definition works for any proper name in the XAML.

peakxamlsl2

Lets see more interesting thing. Peak Definition is very handy when you want to see or modify the defined style or control template. For Example if we right click on the Style defined resource and choose Peak Definition like the following picture:

peakxamlsl31

Inline window will appears and show the style implementation of the selected xaml element. This is very useful and long waited option of XAML editor:

 

peakxamlsl4

Inline windows are edited windows so you can edit or add new code without leaving xaml editor.

This is one of the plenty of the new features coming with the latest version of the Visual Studio 2015. More features in the coming post.

 

 

 

Advertisements

How to extract default file icon in WPF application


documentIconsDemosl1

In Windows every file has default icon, and it is shown in Windows Explorer while browsing files on disk. If you want to grab this icon in WPF application there are several ways. One of the solution is by using ExtractAssociatedIcon from Icon class located in System.Drawing namespace.

The following code shows how to extract default icon from the file specified by file name:

var sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);
var bmpSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
            sysicon.Handle,
            System.Windows.Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
sysicon.Dispose();

Explanation of the code above is straightforward.First we need file path, then we need to call Icon.ExtractAssociatedIcon(filePath) to get Icon object. From the icon object we can create BitmapSource which can be show everywhere in the WPF application.

 

Complete source code demo can be found here.

Drag and Drop Item Outside WPF Application


In WFP applications drag and drop functionality is provided by subscribing several events. First of all you need LeftMouseButtonClick and MouseMove events in order to start Drag and Drop.

This is accomplished by the following code:

private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    this._startPoint = e.GetPosition(null);
}

private void Window_MouseMove(object sender, MouseEventArgs e)
{
    //drag is heppen
    //Prepare for Drag and Drop
    Point mpos = e.GetPosition(null);
    Vector diff = this._startPoint - mpos;

    if (e.LeftButton == MouseButtonState.Pressed &&
        (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
        Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
    {

        //hooking on Mouse Up
        InterceptMouse.m_hookID = InterceptMouse.SetHook(InterceptMouse.m_proc);

        //ataching the event for hadling drop
        this.QueryContinueDrag += queryhandler;
        //begin drag and drop
        DataObject dataObj = new DataObject(this.text1);
        DragDrop.DoDragDrop(this.text1, dataObj, DragDropEffects.Move);

    }
}

As we can see from the code above, first with LeftMouseButtonClick event, we captured the starting point, then by MouseMove event, calculated distance between starting point and the current mouse position. If the distance is big enough we start DragDrop.

When the Drag starts it is necessary to prepare Drag functionality by providing the object to be dragged. In our case (code sample above) we are going to drag TextBox. In order to drag TextBox first we create DragData object by specifying TextBox object in the Constructor, and call DragDrop static method by passing objects we mentioned.
Beside preparing data to be dragged, we need to subscribe to QueryContinueDrag event in order to track dragging status.

This is all we need to prepare Drag and Drop in our application. If we want to drag object out of WPF aplication, we have no enough information to accomplish drop. As soon as the mouse is outside the app, mousemove event is not firing any more. One of the solution of the problem could be capturing the mouse move position outside the WFP application, and when the left mouse button is up, start with dropping item functionality.

In order to track mouse position outside the WPF application we need to hook and subscribe to the messages of whole Windows OS and filter only we are interesting in. Great blog post about how to capture  mouse messages regardless of the  mouse position can be found here.

Implementation of Low Level Mouse Hook in C# blog post can be modified quickly in order to adopt to our case.

First we need a property to indicate when the mouse is outside the application.

public static bool IsMouseOutsideApp 
{
    get;
    set;
}

Then we need to modify HookCallback method so that when the Left mouse button is up, and set the property (IsMouseOutsideApp ) to true if the mouse outside the application.

internal static IntPtr HookCallback( int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam)
    {
        MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));

        //check if POint in main window
        Point pt = new Point(hookStruct.pt.x, hookStruct.pt.y);
        var ptw = App.Current.MainWindow.PointFromScreen(pt);
        var w = App.Current.MainWindow.Width;
        var h = App.Current.MainWindow.Height;
        //if point is outside MainWindow
        if (ptw.X < 0 || ptw.Y < 0 || ptw.X > w || ptw.Y > h)
            IsMouseOutsideApp = true;
        else
            IsMouseOutsideApp = false;
    }
    return CallNextHookEx(m_hookID, nCode, wParam, lParam);
}

The Last thing we need to implement is DragSourceQueryContinueDrag event. The implementation is straightforward:
1. check the keystate value None – this is the case when the mouse is released.
2. unhook from the mouse intercepting messages
3. show the message text based on the result of drag and dropping.

 
/// <summary>
/// Continuosly tracking Dragging mouse position
/// </summary>
/// 
/// 
private void DragSourceQueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
    //when keystate is non, draop is heppen
    if (e.KeyStates == DragDropKeyStates.None)
    {
        //unsubscribe event
        this.QueryContinueDrag -= queryhandler;
        e.Handled = true;
        //Unhooking on Mouse Up
        InterceptMouse.UnhookWindowsHookEx(InterceptMouse.m_hookID);

        //notifiy user about drop result
        Task.Run(
            () =>;
            {
                //Drop hepend outside Instantly app
                if (InterceptMouse.IsMouseOutsideApp)
                    MessageBox.Show("Dragged outside app");
                else
                    MessageBox.Show("Dragged inside app");
            }
            );
    }
}

Complete demo with source code can be found here:

CrossNumber- puzzle with numbers for WP7, Silverlight, Android and Win8 metro game


Recently I decided to start with implementation of my first game which is going to be CrossNumber  puzzle.

clip_image002

CrossNumbers is puzzle game which can be played from 7 year old children to mans in late year who like puzzle and math. The game is going to be for fun as well as for education propose which you can train your brain with math and problem solving. The game will be ported in Silverlight, WP7, Win8 Metro and Android.

Game contains originally designed problems which need to be solved in measured time, with penalty points for failed attempts. The game starts with simple cross number problems and rising its difficulties as you passing levels.

How to enter the number

clip_image004Each game needs input number provided by the player. The numbers are entered by special InputKeyboard showed on the left picture.

Before you input the number you need to select cell by clicking or taping grayed (hidden) cell. Picture left shows selected cell which holds sum of 2 and 6. By clicking on the clip_image005key you enter the correct value. If the value is incorrect the red rectangle will appear.

If you need to enter number greater than 9, you need to use combination of key clip_image006 and certain number.

Example

13=clip_image006[1]+clip_image007

Type of Games

Currently there are two kind of games (curreently on two variant are implemented in alpha version):

· HDV Sum

· Sum to 11

HVD Sum

HDV Sum stands for Horizontal, Vertical and Diagonal summation. This is classic CrossNumber puzzle. The simple problem is depicted below:

Suppose we have 4×4 grid (yellow area), with random numbers in cells. Red bottom and right row/column hold sum of the yellow cell in Horizontal, Vertical and Diagonal (right and left) direction .

clip_image009

If we want to sumthe first yellow column the sum is equal to 7. On the same way we are having sums for the next 2 columns and they are 6 and 8 respectively.

Now we are going to sum in horizontal direction. So, for the first, second and third row we have 4,6 and 13 respectively.

Now remain part is diagonal summation from the top-left to the right-bottom corner and left-bottom to the right-top. The values are 12 and 7.

This type of game will have 3 different grids: 2×2, 3×3 and 4×4 grids.

Sum to 11

The next type game is Sum to 11. This is game which is real ultimate brain puzzle and is not easy as you may think.

The picture below shows the rules for this game. This is math intensive game and represents real challenge for players.

clip_image010

On the upper part there is a 4 of 4by4 grids, which are indexed for constructing the equations bellow. You need to follow equation below in order to solve puzzle successfully. This game will also have some variants probably for summation of 11, 21, 33 and 55.

The game is already in alpha stage of Silverlight and WP7 platform, and it is accessed by very limited number of people. But very soon it will be opened to all who is interesting in game.