2012-01-19 36 views
14

Estoy usando C#/WPF para hacer una aplicación. En esa aplicación, quiero abrir y cerrar la ventana si ocurre un evento en particular para que el usuario de esa aplicación sepa que sucedió algo. ¿Cómo puedo obtener esto en mi aplicación C# WPF?Forzar el parpadeo de la ventana cuando ocurre un evento en particular en C#/WPF

Al igual que en Yahoo Messenger, si recibes un mensaje, la ventana del mensaje parpadea para que te centres, quiero usar ese efecto en mi aplicación.

+0

Soy nuevo en WPF y busqué en Google pero no encontré ninguna solución fácil que pueda entender fácilmente ... –

+0

@Marco Ese enlace muestra cómo hacer que una ventana parpadee en la tarea r, no cómo hacer que una ventana de tamaño regular parpadee. – Rachel

Respuesta

27

intermitente la ventana y la barra de tareas de una manera similar a la mensajería instantánea notificaciones se puede lograr en WPF usando el siguiente código. Utiliza PlatformInvoke llamar a la función API de Windows FlashWindowEx utilizando la manija Win32 del WPF Application.Current.MainWindow

Código

public class FlashWindowHelper 
{ 
    private IntPtr mainWindowHWnd; 
    private Application theApp; 

    public FlashWindowHelper(Application app) 
    { 
     this.theApp = app; 
    } 

    public void FlashApplicationWindow() 
    { 
     InitializeHandle(); 
     Flash(this.mainWindowHWnd, 5); 
    } 

    public void StopFlashing() 
    { 
     InitializeHandle(); 

     if (Win2000OrLater) 
     { 
      FLASHWINFO fi = CreateFlashInfoStruct(this.mainWindowHWnd, FLASHW_STOP, uint.MaxValue, 0); 
      FlashWindowEx(ref fi); 
     } 
    } 

    private void InitializeHandle() 
    { 
     if (this.mainWindowHWnd == IntPtr.Zero) 
     { 
      // Delayed creation of Main Window IntPtr as Application.Current passed in to ctor does not have the MainWindow set at that time 
      var mainWindow = this.theApp.MainWindow; 
      this.mainWindowHWnd = new System.Windows.Interop.WindowInteropHelper(mainWindow).Handle; 
     } 
    } 

    [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="hwnd"></param> 
    /// <returns></returns> 
    public static bool Flash(IntPtr hwnd) 
    { 
     // Make sure we're running under Windows 2000 or later 
     if (Win2000OrLater) 
     { 
      FLASHWINFO fi = CreateFlashInfoStruct(hwnd, FLASHW_ALL | FLASHW_TIMERNOFG, uint.MaxValue, 0); 

      return FlashWindowEx(ref fi); 
     } 
     return false; 
    } 

    private static FLASHWINFO CreateFlashInfoStruct(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="hwnd">The handle of the Window to Flash.</param> 
    /// <param name="count">The number of times to Flash.</param> 
    /// <returns></returns> 
    public static bool Flash(IntPtr hwnd, uint count) 
    { 
     if (Win2000OrLater) 
     { 
      FLASHWINFO fi = CreateFlashInfoStruct(hwnd, FLASHW_ALL | FLASHW_TIMERNOFG, count, 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 Environment.OSVersion.Version.Major >= 5; } 
    } 
} 

Uso

var helper = new FlashWindowHelper(Application.Current); 

// Flashes the window and taskbar 5 times and stays solid 
// colored until user focuses the main window 
helper.FlashApplicationWindow(); 

// Cancels the flash at any time 
helper.StopFlashing(); 
+0

Este es un gran ejemplo ... a excepción de mí, el icono de la barra de tareas parpadea solo una vez por menos de un segundo :( – Julien

+0

¿En qué sistema operativo? Utilicé lo anterior (estaba en la mente de WinXP) y parpadearía 5 segundos, luego permanezca en color naranja. –

+0

Mis disculpas, el identificador de ventana utilizado por su clase era incorrecto para mi proyecto. Lo modifiqué ligeramente para aceptar identificadores personalizados y todo está bien. Muchas gracias! – Julien

6

Puede usar la clase TaskBarItem para hacer que parpadee el icono de la barra de tareas de su aplicación. Éstos son algunos recursos que le ayudarán a lograrlo:
- http://social.msdn.microsoft.com/Forums/en/wpf/thread/369bc5ee-a9a7-493f-978f-27a8ddedea06
- http://www.bobpowell.net/flashbar.htm

A continuación, puede flash, shake, fade-in fade-out o whatever one of the other zillion FX usando WPF animaciones. Es muy simple y no requiere casi ningún código, si tiene Expression Blend, el trabajo se hace aún más fácil.

+0

solo quiero abrir la ventana de WPF y no quiero mostrar el progreso. uso este código pero no me ayudó en mi tarea. ¿Puedes decirme simplemente cómo parpadeé la ventana de WPF en un evento en particular, ya sea que haga clic en el botón o en el parpadeo de la ventana de tiempo específica? –

+0

Respuesta actualizada. No me referí a la barra de progreso, puede hacer que el icono de la barra de tareas parpadee, excepto además de la ventana parpadeante. – Shimmy

+1

Algunos enlaces muertos, por favor arreglarlos. –

Cuestiones relacionadas