C# | Suhail Kaleem

C#

Flash Window in Taskbar via Win32 FlashWindowEx

1

The Windows API (Win32) has the FlashWindowEx method within the User32 library; this method allows you (the developer) to Flash a Window, signifying to the user that some major event occurred within the application that requires their attention. The most common use of this is to flash the window until the user returns focus to the application. However, you can also flash the window a specified number of times, or just keep flashing it until you decide when to stop.

The use of the FlashWindowEx method however isn’t built into the .NET Framework anywhere. In order to access it you need to use the Platform Invoke (PInvoke) features of .NET to “drop” down to the Windows API (Win32) and call it directly. Also, as with many other functionalities in¬†the Windows API¬†(that aren’t directly exposed by .NET) the FlashWindowEx method can be a little tricky to use if you aren’t familiar with working with the Windows API from within .NET.

Now rather than go too deep into the specifics of PInvoke or the Win32 FlashWindowEx method, below is a simple static class in C# that allows you to easily utilize this method. There is actually quite a bit of information needed to explain how to use PInvoke to utilize the Windows API (Win32), so maybe I’ll cover that in a future article.

Here’s some example usage of this static class:

// One this to note with this example usage code, is the “this” keyword is referring to
// the current System.Windows.Forms.Form.

// Flash window until it recieves focus
FlashWindow.Flash(this);

// Flash window 5 times
FlashWindow.Flash(this, 5);

// Start Flashing “Indefinately”
FlashWindow.Start(this);

// Stop the “Indefinate” Flashing
FlashWindow.Stop(this);

One thing to note about the FlashWindowEx method is that it requires (and will only work on) Windows 2000 or later.

Here’s the code for the static class in C#:

public static class FlashWindow
{
[DllImport(“user32.dll”)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FlashWindowEx(ref FLASHWINFO pwfi);

[StructLayout(LayoutKind.Sequential)]
private struct FLASHWINFO
{
/// <summary>
/// The size of the structure in bytes.
/// </summary>
public uint cbSize;
/// <summary>
/// A Handle to the Window to be Flashed. The window can be either opened or minimized.
/// </summary>
public IntPtr hwnd;
/// <summary>
/// The Flash Status.
/// </summary>
public uint dwFlags;
/// <summary>
/// The number of times to Flash the window.
/// </summary>
public uint uCount;
/// <summary>
/// The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate.
/// </summary>
public uint dwTimeout;
}

/// <summary>
/// Stop flashing. The system restores the window to its original stae.
/// </summary>
public const uint FLASHW_STOP = 0;

/// <summary>
/// Flash the window caption.
/// </summary>
public const uint FLASHW_CAPTION = 1;

/// <summary>
/// Flash the taskbar button.
/// </summary>
public const uint FLASHW_TRAY = 2;

/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
public const uint FLASHW_ALL = 3;

/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
public const uint FLASHW_TIMER = 4;

/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
public const uint FLASHW_TIMERNOFG = 12;
/// <summary>
/// Flash the spacified Window (Form) until it recieves focus.
/// </summary>
/// <param name=”form”>The Form (Window) to Flash.</param>
/// <returns></returns>
public static bool Flash(System.Windows.Forms.Form form)
{
// Make sure we’re running under Windows 2000 or later
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_ALL | FLASHW_TIMERNOFG, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}

private static FLASHWINFO Create_FLASHWINFO(IntPtr handle, uint flags, uint count, uint timeout)
{
FLASHWINFO fi = new FLASHWINFO();
fi.cbSize = Convert.ToUInt32(Marshal.SizeOf(fi));
fi.hwnd = handle;
fi.dwFlags = flags;
fi.uCount = count;
fi.dwTimeout = timeout;
return fi;
}

/// <summary>
/// Flash the specified Window (form) for the specified number of times
/// </summary>
/// <param name=”form”>The Form (Window) to Flash.</param>
/// <param name=”count”>The number of times to Flash.</param>
/// <returns></returns>
public static bool Flash(System.Windows.Forms.Form form, uint count)
{
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_ALL, count, 0);
return FlashWindowEx(ref fi);
}
return false;
}

/// <summary>
/// Start Flashing the specified Window (form)
/// </summary>
/// <param name=”form”>The Form (Window) to Flash.</param>
/// <returns></returns>
public static bool Start(System.Windows.Forms.Form form)
{
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_ALL, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}

/// <summary>
/// Stop Flashing the specified Window (form)
/// </summary>
/// <param name=”form”></param>
/// <returns></returns>
public static bool Stop(System.Windows.Forms.Form form)
{
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_STOP, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}

/// <summary>
/// A boolean value indicating whether the application is running on Windows 2000 or later.
/// </summary>
private static bool Win2000OrLater
{
get { return System.Environment.OSVersion.Version.Major >= 5; }
}
}

How to Transfer Fixed Sized Data With Async Sockets

0

Usually data exchange between server and client is done in some special way (or special order). Such an order is called communication protocol.
More information on network and communication protocols can be found here and here

The sample here also uses communication protocol. It is very simple, client prefixes the data with 4 bytes that hold data size. Format of the data that will go to the wire can be shown like this [4 bytes – data size][data – data size].

Here comes implementation with short comments. Asynchronous communication via sockets involves methods like BeginReceive/EndReceive – for data receiving and BeginSend/EndSend for sending. The sample demonstrates only how async sockets work and the fact that data is received in the stream like way.
More information about network programming can be found here

Server

At first we define the state that will be passed between async calls. State is defined as following:


/// Server state holds current state of the client socket

class ServerState
{
     public byte[] Buffer = new byte[512]; //buffer for network i/o
     public int DataSize = 0; //data size to be received by the server
     public bool DataSizeReceived = false; //whether prefix was received
     public MemoryStream Data = new MemoryStream(); //place where data is stored
     public Socket Client;   //client socket
}

Server is listening for the clients using Socket.Accept method.
Here is the server listening loop:


//server listening loop
while (true)
{
 Socket client = serverSocket.Accept();
 ServerState state = new ServerState();

 state.Client = client;
 //issue first receive
 client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None,
  new AsyncCallback(ServerReadCallback), state);
}

When data comes to the client socket ServerReadCallback is called. There server can read received data and process it.

Here is the implementation of that method:


private void ServerReadCallback(IAsyncResult
{
    ServerState state = (ServerState)ar.AsyncState;
    Socket client = state.Client;
    SocketError socketError;

    int dataRead = client.EndReceive(ar, out socketError);
    int dataOffset = 0; //to simplify logic

    if (socketError != SocketError.Success)
    {
       client.Close();
       return;
    }

    if (dataRead <= 0)
    { //connection reset
       client.Close();
       return;
    } 

    if (!state.DataSizeReceived)
    {
       if (dataRead >= 4)
       {   //we received data size prefix
           state.DataSize = BitConverter.ToInt32(state.Buffer, 0);
           state.DataSizeReceived = true;
           dataRead -= 4;
           dataOffset += 4;
       }
    }

    if ((state.Data.Length + dataRead) == state.DataSize)
    {   //we have all the data
        state.Data.Write(state.Buffer, dataOffset, dataRead);

        Console.WriteLine("Data received. Size: {0}", state.DataSize);

        client.Close();
        return;
     }
     else
     {   //there is still data pending, store what we've
         //received and issue another BeginReceive
         state.Data.Write(state.Buffer, dataOffset, dataRead);

         client.BeginReceive(state.Buffer, 0, state.Buffer.Length,
           SocketFlags.None, new AsyncCallback(ServerReadCallback), state);
     }
}

As you can see server implementation is very simple. It receives data size prefix at first and if it is complete (first 4 bytes are received) then proceeds with data receive.

It is very important to always check the number of received bytes. This number can vary.

Client

Client implementation is pretty straightforward. It also has a state that is passed along async operations.


public class ClientState
{
     public Socket Client; //client socket
     public byte[] DataToSend; //data to be trasferred
     public int DataSent = 0; //data already sent
}

The data being sent is prefixed with its size.


  ClientState state = new ClientState();
  state.Client = socket;

  //add prefix to data
  state.DataToSend = new byte[data.Length + 4];
  byte[] prefix = BitConverter.GetBytes(data.Length);
  //copy data size prefix
  Buffer.BlockCopy(prefix, 0, state.DataToSend, 0, prefix.Length);
  //copy the data
  Buffer.BlockCopy(data, 0, state.DataToSend, prefix.Length, data.Length);

  socket.BeginSend(state.DataToSend, 0, state.DataToSend.Length,
    SocketFlags.None, new AsyncCallback(ClientSendCallback), state);

And finally the implementation of ClientSendCallback


private void ClientSendCallback(IAsyncResult ar)
{
    ClientState state = (ClientState)ar.AsyncState;
    SocketError socketError;
    int sentData = state.Client.EndSend(ar, out socketError);

    if ( socketError != SocketError.Success )
    {
       state.Client.Close();
       return;
    }

    state.DataSent += sentData;

    if (state.DataSent != state.DataToSend.Length)
    {   //not all data was sent
        state.Client.BeginSend(state.DataToSend, state.DataSent,
          state.DataToSend.Length - state.DataSent, SocketFlags.None,
            new AsyncCallback(ClientSendCallback), state);
    }
    else
    {   //all data was sent
        Console.WriteLine("All data was sent. Size: {0}",
          state.DataToSend.Length);
             state.Client.Close();
    }
}

As you can see implementation details are very simple.
There are several important things here:

  • Data is received in pieces, you can’t predict how much data you will receive during one method call
  • When using async sockets always pass the same state object in the context of the same client

Update
The code sample above illustrates the idea of tranferring size-prefixed data between client and server in the async way. Please, note that only one message per connection is passed from client to server. To add multiple message handling – server code has to be modified according to your custom the protocol.

Go to Top