Ejemplo n.º 1
0
 public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
 {
     if (values[1] == null || values[1].ToString() == "")
     {
         return(values[0].ToString()[0].ToString());
     }
     else
     {
         try
         {
             using (System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Convert.FromBase64String(values[1].ToString())))
             {
                 PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                 BitmapFrame      frame   = decoder.Frames.First();
                 frame.Freeze();
                 System.Windows.Controls.Image m = new System.Windows.Controls.Image();
                 m.Source = frame;
                 return(m);
             }
         }
         catch (Exception)
         {
             MaterialDesignThemes.Wpf.PackIcon icon = new MaterialDesignThemes.Wpf.PackIcon();
             icon.Kind = MaterialDesignThemes.Wpf.PackIconKind.Account;
             return(icon);
         }
     }
 }
Ejemplo n.º 2
0
        public static async Task <WriteableBitmap> ToBitmapImageAsync(this Stream imageStream, Tuple <int, int> downscale, bool downscaleDipUnits, InterpolationMode mode, bool allowUpscale, ImageInformation imageInformation = null)
        {
            if (imageStream == null)
            {
                return(null);
            }
            using (imageStream)
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    return(imageStream.ResizeImage(downscale.Item1, downscale.Item2, mode, downscaleDipUnits, allowUpscale, imageInformation));
                }
                BitmapDecoder decoder    = NewDecoder(imageStream);
                BitmapFrame   firstFrame = decoder.Frames.First();
                firstFrame.Freeze();
                imageStream.Seek(0L, SeekOrigin.Begin);
                WriteableBitmap bitmap = null;
                if (imageInformation != null)
                {
                    imageInformation.SetCurrentSize(firstFrame.PixelWidth, firstFrame.PixelHeight);
                    imageInformation.SetOriginalSize(firstFrame.PixelWidth, firstFrame.PixelHeight);
                }
                await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(delegate
                {
                    bitmap = new WriteableBitmap(firstFrame);
                    bitmap.Freeze();
                }).ConfigureAwait(continueOnCapturedContext: false);

                return(bitmap);
            }
        }
Ejemplo n.º 3
0
        // All bitmap laoding eventually invokes this static function
        public static BitmapSource GetBitmapFromImageFile(string filePath, Nullable <int> desiredWidthOrHeight, ImageDisplayIntentEnum displayIntent, ImageDimensionEnum imageDimension, out bool isCorruptOrMissing)
        {
            isCorruptOrMissing = true;

            // BitmapCacheOption.None is significantly faster than other options.
            // However, it locks the file as it is being accessed (rather than a memory copy being created when using a cache)
            // This means we cannot do any file operations on it (such as deleting the currently displayed image) as it will produce an access violation.
            // This is ok for TransientLoading, which just temporarily displays the image
            BitmapCacheOption bitmapCacheOption = (displayIntent == ImageDisplayIntentEnum.Ephemeral) ? BitmapCacheOption.None : BitmapCacheOption.OnLoad;

            if (!System.IO.File.Exists(filePath))
            {
                return(Constant.ImageValues.FileNoLongerAvailable.Value);
            }
            try
            {
                // Exception workarounds to consider: see  http://faithlife.codes/blog/2010/07/exceptions_thrown_by_bitmapimage_and_bitmapframe/
                if (desiredWidthOrHeight.HasValue == false)
                {
                    // returns the full size bitmap
                    BitmapFrame frame = BitmapFrame.Create(new Uri(filePath), BitmapCreateOptions.None, bitmapCacheOption);
                    frame.Freeze();
                    isCorruptOrMissing = false;
                    return(frame);
                }

                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                if (imageDimension == ImageDimensionEnum.UseWidth)
                {
                    bitmap.DecodePixelWidth = desiredWidthOrHeight.Value;
                }
                else
                {
                    bitmap.DecodePixelHeight = desiredWidthOrHeight.Value;
                }
                bitmap.CacheOption = bitmapCacheOption;
                bitmap.UriSource   = new Uri(filePath);
                bitmap.EndInit();
                bitmap.Freeze();

                isCorruptOrMissing = false;
                return(bitmap);
            }
            catch (Exception exception)
            {
                // Optional messages for eventual debugging of catch errors,
                if (exception is InsufficientMemoryException)
                {
                    TracePrint.PrintMessage(String.Format("ImageRow/LoadBitmap: exception getting bitmap from file: {0}\n.** Insufficient Memory Exception: {1}.\n--------------\n**StackTrace: {2}.\nXXXXXXXXXXXXXX\n\n", filePath, exception.Message, exception.StackTrace));
                }
                else
                {
                    // TraceDebug.PrintMessage(String.Format("ImageRow/LoadBitmap: General exception: {0}\n.**Unkonwn exception getting bitmap from file: {1}.\n--------------\n**StackTrace: {2}.\nXXXXXXXXXXXXXX\n\n", filePath, exception.Message, exception.StackTrace));
                }
                isCorruptOrMissing = true;
                return(Constant.ImageValues.Corrupt.Value);
            }
        }
Ejemplo n.º 4
0
        void bmp_DownloadFailed(object sender, ExceptionEventArgs e)
        {
            BitmapFrame bmp = (BitmapFrame)sender;
            var         id  = downloadingTiles[bmp];

            downloadingTiles.Remove(bmp);
            UnsubscribeBitmapEvents(bmp);
            bmp.Freeze();

            ReportFailure(id);
        }
Ejemplo n.º 5
0
        public override byte[] getBytes()
        {
            MemoryStream      memStream = new MemoryStream();
            JpegBitmapEncoder encoder   = new JpegBitmapEncoder();
            BitmapFrame       bf        = BitmapFrame.Create(bitmapSource);

            bf.Freeze();
            encoder.Frames.Add(bf);
            encoder.Save(memStream);
            return(memStream.GetBuffer());
        }
Ejemplo n.º 6
0
        void bmp_DownloadCompleted(object sender, EventArgs e)
        {
            BitmapFrame bmp = (BitmapFrame)sender;
            var         id  = downloadingTiles[bmp];

            downloadingTiles.Remove(bmp);
            UnsubscribeBitmapEvents(bmp);
            bmp.Freeze();

            ReportSuccess(bmp, id);
        }
Ejemplo n.º 7
0
        public static BitmapImage GetImagebyBitmapImage(string imgPath, double maxWidth, double maxHeight)
        {
            if (File.Exists(imgPath))
            {
                try
                {
                    double      newCx = 0, newCy = 0;
                    BitmapFrame bf = BitmapFrame.Create(new Uri(imgPath, UriKind.RelativeOrAbsolute), BitmapCreateOptions.DelayCreation | BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
                    newCx = bf.PixelWidth;
                    newCy = bf.PixelHeight;

                    double newWidth  = 0d;
                    double newHeight = 0d;
                    double perWidth  = maxWidth / newCx;
                    double perHeight = maxHeight / newCy;
                    if (perWidth > perHeight)
                    {
                        newWidth  = perHeight * newCx;
                        newHeight = maxHeight;
                    }
                    else
                    {
                        newWidth  = maxWidth;
                        newHeight = perWidth * newCy;
                    }

                    newWidth  = newWidth >= bf.PixelWidth ? bf.PixelWidth : newWidth;
                    newHeight = newHeight >= bf.PixelHeight ? bf.PixelHeight : newHeight;



                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CreateOptions     = BitmapCreateOptions.None;
                    bi.DecodePixelWidth  = (int)newWidth;
                    bi.DecodePixelHeight = (int)newHeight;
                    bi.CacheOption       = BitmapCacheOption.OnLoad;
                    bi.UriSource         = new Uri(imgPath, UriKind.RelativeOrAbsolute);
                    bi.EndInit();
                    bf.Freeze();



                    return(bi);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }

            return(null);
        }
Ejemplo n.º 8
0
        public static byte[] BufferFromImage(BitmapSource image)
        {
            byte[] imageByte = null;

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            BitmapFrame       bf      = BitmapFrame.Create(image);

            bf.Freeze();
            encoder.Frames.Add(bf);

            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                imageByte = ms.GetBuffer();
            }
            return(imageByte);
        }
Ejemplo n.º 9
0
        public static BitmapSource jpegBase64StringToImage(String encoded)
        {
            if (String.IsNullOrEmpty(encoded))
            {
                return(null);
            }

            byte[] bytes = System.Convert.FromBase64String(encoded);

            MemoryStream stream = new MemoryStream(bytes);

            JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
            BitmapFrame       image   = decoder.Frames[0];

            image.Freeze();

            return(image);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Parses the ClipboardItem as an image (BitmapFrame).
        /// </summary>
        public static BitmapFrame ParseImage(ClipboardItem item)
        {
            if (!CanParse(item, AbstractDataFormat.Image))
            {
                throw new ArgumentException("The ClipboardItem does not contain data in the requested format.");
            }

            switch (item.Format)
            {
            case DataFormat.Dib:
                byte[]      dibBytes    = item.GetDataBuffer();
                BitmapFrame imageSource = DIBitmap.CreateBitmapFrameFromDibBytes(dibBytes);
                // Freeze the image to prevent modifications
                // and allow it to be used from different threads.
                imageSource.Freeze();
                return(imageSource);

            default:
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 11
0
        public ImageSource ScaleLogicalImageForDeviceSize(ImageSource image, System.Windows.Size deviceImageSize, BitmapScalingMode scalingMode)
        {
            Validate.IsNotNull(image, "image");
            DrawingGroup drawingGroup = new DrawingGroup();

            drawingGroup.Children.Add(new ImageDrawing(image, new Rect(deviceImageSize)));
            DrawingVisual drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                RenderOptions.SetBitmapScalingMode(drawingGroup, scalingMode);
                drawingContext.DrawDrawing(drawingGroup);
            }
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)deviceImageSize.Width, (int)deviceImageSize.Height, LogicalDpiX, LogicalDpiY, PixelFormats.Default);

            renderTargetBitmap.Render(drawingVisual);
            BitmapFrame bitmapFrame = BitmapFrame.Create(renderTargetBitmap);

            bitmapFrame.Freeze();
            return(bitmapFrame);
        }
Ejemplo n.º 12
0
 public static async Task <BitmapHolder> ToBitmapHolderAsync(this Stream imageStream, Tuple <int, int> downscale, bool downscaleDipUnits, InterpolationMode mode, bool allowUpscale, ImageInformation imageInformation = null)
 {
     if (imageStream == null)
     {
         return(null);
     }
     using (imageStream)
     {
         if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
         {
             WriteableBitmap downscaledImage = imageStream.ResizeImage(downscale.Item1, downscale.Item2, mode, downscaleDipUnits, allowUpscale, imageInformation);
             return(new BitmapHolder(await downscaledImage.ToBytesAsync(), downscaledImage.PixelWidth, downscaledImage.PixelHeight));
         }
         BitmapDecoder decoder    = NewDecoder(imageStream);
         BitmapFrame   firstFrame = decoder.Frames.First();
         firstFrame.Freeze();
         if (imageInformation != null)
         {
             imageInformation.SetCurrentSize(firstFrame.PixelWidth, firstFrame.PixelHeight);
             imageInformation.SetOriginalSize(firstFrame.PixelWidth, firstFrame.PixelHeight);
         }
         return(new BitmapHolder(await firstFrame.ToBytesAsync(), firstFrame.PixelWidth, firstFrame.PixelHeight));
     }
 }
Ejemplo n.º 13
0
        /*
         * Metodo eseguito da un thread in background per la ricezione dati dal socket
         * La signature della funzione deve rispettare il delegato ThreadStart
         */
        public void ThreadFcn()
        {
            int nread = 0;

            try {
                Byte[] myReadBuffer = new Byte[1024];

                // Ricezione modifiche dal server
                while (!stop)
                {
                    Console.WriteLine("In attesa di ricevere dati dal server...");

                    // Ricezione tipo modifica: u_short
                    nread = Stream.Read(myReadBuffer, 0, sizeof(ushort));

                    if (!isReadCorrect(nread, sizeof(ushort)))
                    {
                        return;
                    }

                    // Conversione Network To Host Order
                    ushort mod_convertito = BitConverter.ToUInt16(myReadBuffer, 0);
                    int    mod            = IPAddress.NetworkToHostOrder((short)mod_convertito);
                    Console.WriteLine("Tipo modifica: {0}", mod);

                    // Ricezione PID del processo: DWORD
                    // La dimensione della DWORD è pari a quella di un uint in C#
                    nread = Stream.Read(myReadBuffer, 0, sizeof(uint));

                    if (!isReadCorrect(nread, sizeof(uint)))
                    {
                        return;
                    }

                    uint pid = BitConverter.ToUInt32(myReadBuffer, 0);

                    Console.WriteLine("PID: {0}", pid);

                    // Switch sul tipo della modifica
                    switch (mod)
                    {
                    // Caso 0: aggiunta di una nuova applicazione
                    case 0:
                        // Ricezione lunghezza del nome dell'applicazione
                        nread = Stream.Read(myReadBuffer, 0, sizeof(int));

                        if (!isReadCorrect(nread, sizeof(uint)))
                        {
                            return;
                        }

                        // Conversione Network To Host Order
                        int len_conv = BitConverter.ToInt32(myReadBuffer, 0);
                        Console.WriteLine("lunghezza convertita: {0}", len_conv);
                        int name_len = IPAddress.NetworkToHostOrder(len_conv);
                        Console.WriteLine("lunghezza nome: {0}", name_len);

                        Byte[] buffer_name = new Byte[name_len];

                        String app_name = String.Empty;

                        // Ricezione del nome dell'applicazione
                        nread = Stream.Read(buffer_name, 0, name_len);

                        if (!isReadCorrect(nread, name_len))
                        {
                            return;
                        }

                        // Conversione in String
                        try {
                            app_name = System.Text.UnicodeEncoding.Unicode.GetString(buffer_name);
                            app_name = app_name.Replace("\0", String.Empty);
                        } catch (ArgumentException) {
                            app_name = "Senza nome";
                        }

                        Console.WriteLine("Nome dell'app: {0}", app_name);

                        // Ricezione lunghezza dell'icona
                        nread = Stream.Read(myReadBuffer, 0, sizeof(int));

                        if (!isReadCorrect(nread, sizeof(uint)))
                        {
                            return;
                        }

                        // Creazione dell'oggetto ApplicationItem con icona di default
                        ApplicationItem app = new ApplicationItem(item.ContainerTab.MainWindow.defaultIcon);
                        app.PID  = pid;
                        app.Name = app_name;

                        // Conversione Network To Host Order
                        int icon_conv = BitConverter.ToInt32(myReadBuffer, 0);
                        int icon_len  = IPAddress.NetworkToHostOrder(icon_conv);
                        Console.WriteLine("lunghezza icona convertita: {0}", icon_len);

                        // Se la dimensione dell'icona è valida, si sostituisce a quella di default
                        if (icon_len != 0 && icon_len < 1048576)
                        {
                            Console.WriteLine("Icona presente");

                            // Ricezione icona (in blocchi da 1024 byte)
                            Byte[] buffer_ICON = new Byte[icon_len];
                            int    tot = 0, toread = 1024;
                            while (tot != icon_len)
                            {
                                if (toread > icon_len - tot)
                                {
                                    toread = icon_len - tot;
                                }
                                nread = Stream.Read(buffer_ICON, tot, toread);

                                if (nread == 0)
                                {
                                    Console.WriteLine("Connessione chiusa durante lettura");
                                    return;
                                }
                                tot += nread;
                            }

                            if (tot != icon_len)
                            {
                                Console.WriteLine("Read fallita: {0}", nread);
                                item.ContainerTab.MainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                                    new Action(() => { item.ContainerTab.MainWindow.CloseTab(item.ContainerTab); }));
                            }

                            // Codice unsafe perché si fa uso di puntatori
                            // Lettura dell'icona tramite la funzione importata e conversione in bitmap WPF
                            unsafe
                            {
                                fixed(byte *buffer = &buffer_ICON[0])
                                {
                                    IntPtr Hicon = CreateIconFromResourceEx((IntPtr)buffer, (uint)icon_len, 1, 0x00030000, 48, 48, 0);

                                    if (Hicon != null)
                                    {
                                        BitmapFrame bitmap = BitmapFrame.Create(Imaging.CreateBitmapSourceFromHIcon(Hicon, new Int32Rect(0, 0, 48, 48), BitmapSizeOptions.FromEmptyOptions()));
                                        if (bitmap.CanFreeze)
                                        {
                                            bitmap.Freeze();
                                            app.Icon = bitmap;
                                        }
                                        DestroyIcon(Hicon);
                                    }
                                }
                            }
                        }

                        // Aggiunta nuova applicazione e notifica del cambiamento nella lista

                        item.Dispatcher.Invoke(DispatcherPriority.Send,
                                               new Action(() => { lock (item.applications) { item.applications.Add(app); } }));

                        item.Dispatcher.Invoke(DispatcherPriority.Send,
                                               new Action(() => {
                            item.listView_CollectionChanged(item.listView,
                                                            new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, app));
                        }));

                        break;

                    // Caso 1: rimozione di un'applicazione
                    case 1:
                        Console.WriteLine("Modifica: Rimozione");

                        // Rimozione dell'applicazione dalla lista
                        Monitor.Enter(item.applications);
                        foreach (ApplicationItem appItem in item.applications)
                        {
                            if (appItem.PID == pid)
                            {
                                Console.WriteLine("Rimozione applicazione: {0}", appItem.Name);
                                Monitor.Exit(item.applications);
                                this.item.Dispatcher.Invoke(DispatcherPriority.Send,
                                                            new Action(() => { lock (item.applications) { this.item.applications.Remove(appItem); } }));
                                Monitor.Enter(item.applications);
                                break;
                            }
                        }
                        Monitor.Exit(item.applications);
                        break;

                    // Caso 3: cambio di focus
                    case 2:
                        Console.WriteLine("Modifica: Change Focus");

                        // Pulizia della selezione precedente
                        this.item.ContainerTab.MainWindow.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { this.item.listView.SelectedItem = null; }));


                        // Applicazione che perde il focus
                        this.item.ContainerTab.MainWindow.Dispatcher.Invoke(DispatcherPriority.Send,
                                                                            new Action(() => {
                            // Aggiornamento lista app in foreground
                            int index = this.item.ContainerTab.MainWindow.foregroundApps.IndexOf(new ForegroundApp(item.ContainerTab.foregroundApp, 0));
                            if (index != -1)
                            {
                                if (--this.item.ContainerTab.MainWindow.foregroundApps[index].Count <= 0)
                                {
                                    this.item.ContainerTab.MainWindow.foregroundApps.RemoveAt(index);
                                }
                            }
                        }));
                        // Ricerca delle applicazioni coinvolte nel cambiamento
                        Monitor.Enter(item.applications);
                        foreach (ApplicationItem appItem in item.applications)
                        {
                            // Applicazione che guadagna il focus
                            if (appItem.PID == pid)
                            {
                                Console.WriteLine("Pid: {0} - applicazione: {1}", pid, appItem.Name);
                                Monitor.Exit(item.applications);
                                this.item.ContainerTab.MainWindow.Dispatcher.Invoke(DispatcherPriority.Send,
                                                                                    new Action(() => {
                                    lock (item.applications) {
                                        // Evidenziazione elemento nella tab
                                        appItem.IsFocused = true; this.item.listView.SelectedItem = appItem;
                                        this.item.ContainerTab.foregroundApp = appItem.Name;
                                        // Aggiornamento lista delle app in foreground
                                        int index = this.item.ContainerTab.MainWindow.foregroundApps.IndexOf(new ForegroundApp(appItem.Name, 0));
                                        if (index != -1)
                                        {
                                            this.item.ContainerTab.MainWindow.foregroundApps[index].Count++;
                                        }
                                        else
                                        {
                                            ForegroundApp newapp = new ForegroundApp(appItem.Name, 1);
                                            this.item.ContainerTab.MainWindow.foregroundApps.Add(newapp);
                                            if (!this.item.ContainerTab.MainWindow.foregroundBox.IsEnabled)
                                            {
                                                this.item.ContainerTab.MainWindow.foregroundBox.SelectedItem = newapp;
                                            }
                                        }
                                    }
                                }));
                                Monitor.Enter(item.applications);
                            }
                            else if (appItem.IsFocused)
                            {
                                appItem.IsFocused = false;
                            }
                        }
                        Monitor.Exit(item.applications);
                        // Aggiornamento delle percentuali
                        item.Dispatcher.Invoke(DispatcherPriority.Send,
                                               new Action(() => { item.percentageUpdate(); }));
                        break;

                    case 3:
                        break;

                    default:
                        Console.WriteLine("Modifica sconosciuta");
                        break;
                    }
                }
                Console.WriteLine("Thread - terminata ricezione dati dal server");
            } catch (NullReferenceException) {
                ExceptionHandler.ReceiveConnectionError(item);
            } catch (IOException) {
                ExceptionHandler.ReceiveConnectionError(item);
            } catch (ObjectDisposedException) {
                ExceptionHandler.ReceiveConnectionError(item);
            } catch (ArgumentOutOfRangeException) {
                ExceptionHandler.ReceiveConnectionError(item);
            } catch (OutOfMemoryException) {
                ExceptionHandler.MemoryError(item.ContainerTab.MainWindow);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Funzione eseguita da un thread in background: riceve dati dal socket
        /// </summary>
        public void SocketThreadListen()
        {
            int n = 0;

            try
            {
                Byte[] readBuffer = new Byte[1024];

                while (!stop)
                {
                    Console.WriteLine("In attesa di ricevere dati dal server...");

                    // Ricezione del tipo di modifica effettuata
                    n = Stream.Read(readBuffer, 0, sizeof(ushort));

                    if (!readSuccessful(n, sizeof(ushort)))
                    {
                        return;
                    }

                    // Conversione del buffer nell'ordine dei byte dell'host (Precedentemente era in ordine di rete)
                    ushort conv_mod         = BitConverter.ToUInt16(readBuffer, 0);
                    int    ModificationType = IPAddress.NetworkToHostOrder((short)conv_mod);
                    Console.WriteLine("Tipo della modifica: {0}", ModificationType);

                    // Ricezione del PID del processo. E' una DWORD che ha dimensioni pari ad uint
                    n = Stream.Read(readBuffer, 0, sizeof(uint));

                    if (!readSuccessful(n, sizeof(uint)))
                    {
                        return;
                    }

                    uint PID = BitConverter.ToUInt32(readBuffer, 0);

                    Console.WriteLine("PID: {0}", PID);

                    // Switch sul tipo di modifica
                    switch (ModificationType)
                    {
                    // CASO 0: Aggiunta di una nuova applicazione
                    case 0:

                        // Lettura della lunghezza del nome dell'applicazione
                        n = Stream.Read(readBuffer, 0, sizeof(int));

                        if (!readSuccessful(n, sizeof(uint)))
                        {
                            return;
                        }

                        // Conversione della lunghezza del nome in ordine dell'host
                        int conv_length = BitConverter.ToInt32(readBuffer, 0);
                        Console.WriteLine("Lunghezza convertita: {0}", conv_length);
                        int NameLength = IPAddress.NetworkToHostOrder(conv_length);
                        Console.WriteLine("Lunghezza nome: {0}", NameLength);

                        Byte[] NameBuffer = new Byte[NameLength];

                        String AppName = String.Empty;

                        // Lettura del nome dell'applicazione
                        n = Stream.Read(NameBuffer, 0, NameLength);

                        if (!readSuccessful(n, NameLength))
                        {
                            return;
                        }

                        try
                        {
                            // Conversione in stringa
                            AppName = System.Text.UnicodeEncoding.Unicode.GetString(NameBuffer);
                            AppName = AppName.Replace("\0", String.Empty);
                        }
                        catch (ArgumentException)
                        {
                            AppName = "Nessun nome";
                        }

                        Console.WriteLine("Nome dell'applicazione: {0}", AppName);

                        // Lettura della lunghezza dell'icona

                        n = Stream.Read(readBuffer, 0, sizeof(int));

                        if (!readSuccessful(n, sizeof(uint)))
                        {
                            return;
                        }

                        AppItem app = new AppItem(Item.ServerTab.MainWndw.DefaultIcon);
                        app.PID  = PID;
                        app.Name = AppName;

                        int conv_icon  = BitConverter.ToInt32(readBuffer, 0);
                        int IconLength = IPAddress.HostToNetworkOrder(conv_icon);
                        Console.WriteLine("Lunghezza dell'icona: {0}", IconLength);

                        // Se la dimensione è valida la si sostituisce a quella di default
                        if (IconLength != 0 && IconLength < 1048576)
                        {
                            Console.WriteLine("Icona valida trovata");

                            // Lettura dell'icona dallo stream in blocchi da 1024 byte
                            Byte[] BufferIcon = new Byte[IconLength];

                            int TotalRead = 0;
                            int ToRead    = 1024;

                            while (TotalRead != IconLength)
                            {
                                if (ToRead > IconLength - TotalRead)
                                {
                                    ToRead = IconLength - TotalRead;
                                }

                                n = Stream.Read(BufferIcon, TotalRead, ToRead);

                                if (n == 0)
                                {
                                    Console.WriteLine("Connessione persa durante la lettura dell'icona");
                                    return;
                                }

                                TotalRead += n;
                            }

                            if (TotalRead != IconLength)
                            {
                                Console.WriteLine("Si è verificato un errore durante la lettura dell'icona");
                                Item.ServerTab.MainWndw.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                                {
                                    Item.ServerTab.MainWndw.CloseTab(Item.ServerTab);
                                }));
                            }

                            unsafe
                            {
                                fixed(byte *buffer = &BufferIcon[0])
                                {
                                    IntPtr Hicon = CreateIconFromResourceEx((IntPtr)buffer, (uint)IconLength, 1, 0x00030000, 48, 48, 0);

                                    if (Hicon != null)
                                    {
                                        BitmapFrame bitmap = BitmapFrame.Create(Imaging.CreateBitmapSourceFromHIcon(Hicon, new Int32Rect(0, 0, 48, 48), BitmapSizeOptions.FromEmptyOptions()));
                                        if (bitmap.CanFreeze)
                                        {
                                            bitmap.Freeze();
                                            app.Icon = bitmap;
                                        }

                                        DestroyIcon(Hicon);
                                    }
                                }
                            }
                        }


                        // Aggiunta di una nuova applicazione e notifica del cambiamento nella lista
                        Item.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() =>
                        {
                            lock (Item.Applications)
                            {
                                Item.Applications.Add(app);
                            }
                        }));

                        Item.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() =>
                        {
                            Item.ApplistRerrangeView(Item.Applist, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, app));
                        }));

                        break;

                    // Caso 1: rimozione di un'applicazione
                    case 1:
                        Console.WriteLine("Modifica: Rimozione");

                        // Rimozione dell'applicazione dalla lista
                        Monitor.Enter(Item.Applications);
                        foreach (AppItem appItem in Item.Applications)
                        {
                            if (appItem.PID == PID)
                            {
                                Console.WriteLine("Rimozione applicazione: {0}", appItem.Name);
                                Monitor.Exit(Item.Applications);
                                this.Item.Dispatcher.Invoke(DispatcherPriority.Send,
                                                            new Action(() => { lock (Item.Applications) { this.Item.Applications.Remove(appItem); } }));
                                Monitor.Enter(Item.Applications);
                                break;
                            }
                        }
                        Monitor.Exit(Item.Applications);
                        break;

                    // Caso 3: cambio di focus
                    case 2:
                        Console.WriteLine("Modifica: Change Focus");

                        // Pulizia della selezione precedente
                        this.Item.ServerTab.MainWndw.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { this.Item.Applist.SelectedItem = null; }));


                        // Applicazione che perde il focus
                        this.Item.ServerTab.MainWndw.Dispatcher.Invoke(DispatcherPriority.Send,
                                                                       new Action(() =>
                        {
                            // Aggiornamento lista app in foreground
                            int index = this.Item.ServerTab.MainWndw.ForegroundApps.IndexOf(new ForegroundApp(Item.ServerTab.ForegroundApp, 0));
                            if (index != -1)
                            {
                                if (--this.Item.ServerTab.MainWndw.ForegroundApps[index].Count <= 0)
                                {
                                    this.Item.ServerTab.MainWndw.ForegroundApps.RemoveAt(index);
                                }
                            }
                        }));
                        // Ricerca delle applicazioni coinvolte nel cambiamento
                        Monitor.Enter(Item.Applications);
                        foreach (AppItem appItem in Item.Applications)
                        {
                            // Applicazione che guadagna il focus
                            if (appItem.PID == PID)
                            {
                                Console.WriteLine("Pid: {0} - applicazione: {1}", PID, appItem.Name);
                                Monitor.Exit(Item.Applications);
                                this.Item.ServerTab.MainWndw.Dispatcher.Invoke(DispatcherPriority.Send,
                                                                               new Action(() =>
                                {
                                    lock (Item.Applications)
                                    {
                                        // Evidenziazione elemento nella tab
                                        appItem.HasFocus = true;
                                        this.Item.Applist.SelectedItem    = appItem;
                                        this.Item.ServerTab.ForegroundApp = appItem.Name;
                                        // Aggiornamento lista delle app in foreground
                                        int index = this.Item.ServerTab.MainWndw.ForegroundApps.IndexOf(new ForegroundApp(appItem.Name, 0));
                                        if (index != -1)
                                        {
                                            this.Item.ServerTab.MainWndw.ForegroundApps[index].Count++;
                                        }
                                        else
                                        {
                                            ForegroundApp newapp = new ForegroundApp(appItem.Name, 1);
                                            this.Item.ServerTab.MainWndw.ForegroundApps.Add(newapp);
                                            if (!this.Item.ServerTab.MainWndw.ForegroundAppsBox.IsEnabled)
                                            {
                                                this.Item.ServerTab.MainWndw.ForegroundAppsBox.SelectedItem = newapp;
                                            }
                                        }
                                    }
                                }));
                                Monitor.Enter(Item.Applications);
                            }
                            else if (appItem.HasFocus)
                            {
                                appItem.HasFocus = false;
                            }
                        }
                        Monitor.Exit(Item.Applications);
                        // Aggiornamento delle percentuali
                        Item.Dispatcher.Invoke(DispatcherPriority.Send,
                                               new Action(() => { Item.PercentageRefresh(); }));
                        break;

                    case 3:
                        break;

                    default:
                        Console.WriteLine("Modifica sconosciuta");
                        break;
                    }
                }
                Console.WriteLine("Thread - terminata ricezione dati dal server");
            }
            catch (NullReferenceException)
            {
                ExceptionHandler.ReceiveConnectionError(Item);
            }
            catch (IOException)
            {
                ExceptionHandler.ReceiveConnectionError(Item);
            }
            catch (ObjectDisposedException)
            {
                ExceptionHandler.ReceiveConnectionError(Item);
            }
            catch (ArgumentOutOfRangeException)
            {
                ExceptionHandler.ReceiveConnectionError(Item);
            }
            catch (OutOfMemoryException)
            {
                ExceptionHandler.MemoryError(Item.ServerTab.MainWndw);
            }
        }
Ejemplo n.º 15
0
        public void ResizeImageCode()
        {
            ImageReadyToDisplay = true;
            ImageError          = false;
            GetMaxSize();
            bool DisplayedMessage = false;

            try
            {
                DisplayedMessage = false;
                ErrorMessage     = "Resize Error.";
                FileInfo fileInfo = ImageList[ImageIdxList[ImageIdxListPtr]];
                decoder = null;

                if (fileInfo.Length > 20000000)
                {
                    DisplayedMessage = true;
                    topTextBoxClass.messageDisplayStart("Loading large image : " + fileInfo.Name + " Length: " + fileInfo.Length.ToString("N0") + " Bytes", -1, false, true);
                    decoder = LoadLargeImage(fileInfo);
                }
                else
                {
                    memStream = new MemoryStream(File.ReadAllBytes(fileInfo.FullName));
                    memStream.Seek(0, SeekOrigin.Begin);

                    decoder = BitmapDecoder.Create(memStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnDemand);
                }
                photo = decoder.Frames[0];
                imageOriginalHeight = photo.PixelHeight;
                imageOriginalWidth  = photo.PixelWidth;
                widthAspect         = ScreenMaxWidth / imageOriginalWidth;
                heightAspect        = ScreenMaxHeight / imageOriginalHeight;
                if (widthAspect > heightAspect)
                {
                    widthAspect = heightAspect;
                }
                else
                {
                    heightAspect = widthAspect;
                }
                target       = new TransformedBitmap(photo, new ScaleTransform(widthAspect, heightAspect, 0, 0));
                displayPhoto = BitmapFrame.Create(target);
                photo        = null;
                decoder      = null;
                target       = null;
                displayPhoto.Freeze();
                DisplayPicInfoDpiX   = (int)displayPhoto.DpiX;
                DisplayPicInfoDpiY   = (int)displayPhoto.DpiY;
                DisplayPicInfoHeight = displayPhoto.PixelHeight;
                DisplayPicInfoWidth  = displayPhoto.PixelWidth;

                if (DisplayPicInfoDpiX != DisplayPicInfoDpiY)
                {
                    ErrorMessage = "DPI Error.";
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                if (memStream != null)
                {
                    memStream.Dispose();
                }
                memStream    = null;
                ImageError   = true;
                displayPhoto = null;
                photo        = null;
                decoder      = null;
                target       = null;
                string srcName  = Path.GetFileName(ImageList[ImageIdxList[ImageIdxListPtr]].FullName);
                string destName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), srcName);
                try
                {
                    //File.Copy(ImageList[ImageIdxList[ImageIdxListPtr]].FullName, destName);
                    ErrorMessage = srcName + " " + ErrorMessage + " Exception details: " + e.Message;
                }
                catch
                {
                    ErrorMessage = srcName + " " + ErrorMessage + " Exception details: " + e.Message;
                }
            }
            finally
            {
                if (DisplayedMessage)
                {
                    topTextBoxClass.messageDisplayEndUninterruptable(new Action(() =>
                    {
                        progressBar.Visibility = Visibility.Hidden;
                    }));
                }
            }
        }
Ejemplo n.º 16
0
        internal static byte[] SaveWithCodecs(byte[] imageData, ImageEngineFormat format, int width, int height, AlphaSettings alphaSetting)
        {
            var image = UsefulThings.WPF.Images.CreateWriteableBitmap(imageData, width, height);

            image.Freeze();
            BitmapFrame frame = null;

            if (alphaSetting == AlphaSettings.RemoveAlphaChannel)
            {
                frame = BitmapFrame.Create(new FormatConvertedBitmap(image, PixelFormats.Bgr32, image.Palette, 0));
            }
            else if (format == ImageEngineFormat.BMP || format == ImageEngineFormat.PNG)
            {
                // Check if there's any alpha.
                bool anyAlpha = false;
                for (int i = 3; i < imageData.Length; i += 4)
                {
                    if (imageData[i] != 255)
                    {
                        anyAlpha = true;
                        break;
                    }
                }

                if (!anyAlpha)
                {
                    frame = BitmapFrame.Create(new FormatConvertedBitmap(image, PixelFormats.Bgr32, image.Palette, 0));
                }
            }
            else
            {
                frame = BitmapFrame.Create(image);
            }

            frame.Freeze();

            // KFreon: Choose encoder based on desired format.
            BitmapEncoder encoder            = null;
            int           estimatedImageSize = 0;

            int estimateHeaderSize = 1024;

            switch (format)
            {
            case ImageEngineFormat.BMP:
                encoder            = new BmpBitmapEncoder();
                estimatedImageSize = estimateHeaderSize + width * height * 4;      // Fairly good estimation
                break;

            case ImageEngineFormat.JPG:
                encoder = new JpegBitmapEncoder();
                ((JpegBitmapEncoder)encoder).QualityLevel = JPGCompressionSetting;
                estimatedImageSize = estimateHeaderSize + width * height / 6;      // Estimation
                break;

            case ImageEngineFormat.PNG:
                encoder            = new PngBitmapEncoder();
                estimatedImageSize = estimateHeaderSize + width * height / 2;      // Estimation
                break;

            case ImageEngineFormat.GIF:
                encoder            = new GifBitmapEncoder();
                estimatedImageSize = estimateHeaderSize + width * height / 5;      // Estimation
                break;

            case ImageEngineFormat.TIF:
                encoder            = new TiffBitmapEncoder();
                estimatedImageSize = estimateHeaderSize + width * height;     // Esimation
                break;

            default:
                throw new InvalidOperationException($"Unable to encode format: {format} using Windows 8.1 Codecs.");
            }

            encoder.Frames.Add(frame);
            using (MemoryStream ms = new MemoryStream(estimatedImageSize))  // Big enough to reduce memory copying.
            {
                encoder.Save(ms);
                return(ms.ToArray());
            }
        }
Ejemplo n.º 17
0
    public void EncodeAndSave(Icon i, string name, string filePath)
    {
        bool PixelArt = true;

        int Width  = i.Width;
        int Height = i.Height;
        int Scale  = i.Scale;

        if (string.IsNullOrEmpty(_FileName))
        {
            MessageBox.Show("You should load an image first");
            return;
        }
        ;

        if (string.IsNullOrEmpty(filePath))
        {
            filePath = System.IO.Path.GetDirectoryName(_FileName);
        }
        else
        {
            if (!filePath.Contains(":"))
            {
                filePath = System.IO.Path.ChangeExtension(_FileName, "").TrimEnd(new char[] { '.' }) + @"\" + filePath;
            }
            ;
        };

        if (!System.IO.Directory.Exists(filePath))
        {
            System.IO.Directory.CreateDirectory(filePath);
        }
        ;

        // - - -  - - -

        Orientation orientation = Orientation.Square;

        if (Width > Height)
        {
            orientation = Orientation.Landscape;
            Width       = Height;
        }
        ;

        if (Width < Height)
        {
            orientation = Orientation.Portrait;
            Height      = Width;
        }
        ;

        int width  = Width * Scale / 100;
        int height = Height * Scale / 100;

        // Create BitmapFrame for Icon

        RenderTargetBitmap rtb = new RenderTargetBitmap(i.Width, i.Height, 96.0, 96.0, PixelFormats.Pbgra32);

        // Use DrawingGroup for high quality rendering
        // See: http://www.olsonsoft.com/blogs/stefanolson/post/Workaround-for-low-quality-bitmap-resizing-in-WPF-4.aspx
        var group = new DrawingGroup();

        //if (PixelArt)
        //{
        //   RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.LowQuality);
        //}
        //else
        {
            RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality);
        };

        switch (orientation)
        {
        case Orientation.Square:
            group.Children.Add(new ImageDrawing(ImageSource, new Rect(new Point(), new Size(Width, Height))));
            break;

        case Orientation.Landscape:
            group.Children.Add(new ImageDrawing(ImageSource, new Rect(new Point((i.Width - width) / 2, (i.Height - height) / 2), new Size(width, height))));
            break;

        case Orientation.Portrait:
            group.Children.Add(new ImageDrawing(ImageSource, new Rect(new Point((i.Width - width) / 2, (i.Height - height) / 2), new Size(width, height))));
            break;
        }
        ;

        var dv = new DrawingVisual();

        using (DrawingContext dc = dv.RenderOpen())
        {
            if (orientation != Orientation.Square)
            {
                if (!IsTransparent(this.ImageSource))
                {
                    Color color = GetPixel(this.ImageSource, 0, 0);
                    // Color color = Colors.Azure;

                    Brush brush = new SolidColorBrush(color);
                    Pen   pen   = new Pen(brush, 1);

                    dc.DrawRectangle(brush, pen, new Rect(new Point(), new Size(i.Width, i.Height)));
                }
                ;
            }
            ;

            if (Glow)
            {
                Brush _whiteBrush = new RadialGradientBrush(Color.FromArgb(255, 255, 255, 255), Color.FromArgb(0, 255, 255, 255));
                var   pen         = new Pen(new SolidColorBrush(Colors.Transparent), 1);

                dc.DrawEllipse(_whiteBrush, pen, new Point(i.Width / 2, i.Height / 2), i.Width / 2, i.Height / 2);
            }
            ;

            dc.DrawDrawing(group);
        };

        rtb.Render(dv);
        BitmapFrame bmf = BitmapFrame.Create(rtb);

        bmf.Freeze();

        // - - -  - - -

        if (name.Contains(@"\"))
        {
            filePath = filePath + "\\" + name.Split(new char[] { '\\' })[0];
            name     = name.Split(new char[] { '\\' })[1];

            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }
            ;
        }
        ;

        // - - -  - - -

        string     fileOut = filePath + "\\" + name;
        FileStream stream  = new FileStream(fileOut, FileMode.Create);

        PngBitmapEncoder encoder = new PngBitmapEncoder();

        encoder.Frames.Add(bmf);
        encoder.Save(stream);
        stream.Close();
    }
Ejemplo n.º 18
0
        //metodo eseguito da un thread in background per la ricezione dati dal socket
        public void ThreadFcn()            //la signature della funzione deve rispettare il tipo delegate
        {
            int nread = 0;

            Byte[] myReadBuffer = new Byte[1024];
            try {
                //Ricezione modifiche dal server
                while (!stop)
                {
                    Console.WriteLine("In attesa di ricevere dati dal server...");

                    //Ricezione tipo modifica e PID : u_short + DWORD

                    nread = Stream.Read(myReadBuffer, 0, sizeof(ushort));     //catturare IOException

                    if (nread == 0)
                    {
                        Console.WriteLine("Connessione chiusa durante lettura");

                        break;
                    }
                    else if (nread != sizeof(ushort))
                    {
                        Console.WriteLine("Read fallita");
                        //Il client chiude
                        mainWindow.atClosingTime();
                    }

                    //ha letto il tipo di modifica
                    ushort mod_convertito = BitConverter.ToUInt16(myReadBuffer, 0);
                    Console.WriteLine("mod_convertito: {0}", mod_convertito);
                    int mod = IPAddress.NetworkToHostOrder((short)mod_convertito);
                    Console.WriteLine("Tipo modifica: {0}", mod);

                    //Leggo il PID del processo
                    nread = Stream.Read(myReadBuffer, 0, sizeof(uint)); //leggo la dimensione di un DWORD(long in c++), uint (c#)

                    if (nread == 0)
                    {
                        Console.WriteLine("Connessione chiusa durante lettura");

                        break;
                    }
                    else if (nread != sizeof(uint))
                    {
                        Console.WriteLine("Read fallita");
                        mainWindow.atClosingTime();
                    }

                    //salvo il pid
                    uint pid = BitConverter.ToUInt32(myReadBuffer, 0);

                    Console.WriteLine("PID: {0}", pid);

                    switch (mod)
                    {
                    case 0:    //ricevo lunghezza del nome dell'applicazione
                        nread = Stream.Read(myReadBuffer, 0, sizeof(int));

                        if (nread == 0)
                        {
                            Console.WriteLine("Connessione chiusa durante lettura");

                            break;
                        }
                        else if (nread != sizeof(int))
                        {
                            Console.WriteLine("Read fallita");
                            mainWindow.atClosingTime();
                        }

                        //salvataggio lunghezza del nome
                        int len_conv = BitConverter.ToInt32(myReadBuffer, 0);
                        Console.WriteLine("lunghezza convertita: {0}", len_conv);
                        int name_len = IPAddress.NetworkToHostOrder(len_conv);
                        Console.WriteLine("lunghezza nome: {0}", name_len);

                        Byte[] buffer_name = new Byte[name_len];

                        String app_name = String.Empty;

                        //Lettura del nome dal socket
                        nread = Stream.Read(buffer_name, 0, name_len);

                        if (nread == 0)
                        {
                            Console.WriteLine("Connessione chiusa durante lettura");

                            break;
                        }
                        else if (nread != name_len)
                        {
                            Console.WriteLine("Read fallita");
                            mainWindow.atClosingTime();
                        }

                        //conversione in string
                        app_name = System.Text.UnicodeEncoding.Unicode.GetString(buffer_name);
                        app_name = app_name.Replace("\0", String.Empty);

                        Console.WriteLine("Nome dell'app: {0}", app_name);

                        //ricevo lunghezza dell'icona

                        nread = Stream.Read(myReadBuffer, 0, sizeof(int));

                        if (nread == 0)
                        {
                            Console.WriteLine("Connessione chiusa durante lettura");

                            break;
                        }
                        else if (nread != sizeof(int))
                        {
                            Console.WriteLine("Read fallita");
                            mainWindow.atClosingTime();
                        }

                        ApplicationItem app = new ApplicationItem(mainWindow.defaultIcon);
                        app.PID  = pid;
                        app.Name = app_name;

                        //conversione icon_length in formato host
                        int icon_conv = BitConverter.ToInt32(myReadBuffer, 0);
                        int icon_len  = IPAddress.NetworkToHostOrder(icon_conv);
                        Console.WriteLine("lunghezza icona convertita: {0}", icon_len);

                        //Sostituire l'icona di default
                        if (icon_len != 0)
                        {
                            Console.WriteLine("Icona presente");

                            //Salvataggio icona
                            Byte[] buffer_ICON = new Byte[icon_len];
                            int    tot = 0, toread = 1024;
                            while (tot != icon_len)
                            {
                                if (toread > icon_len - tot)
                                {
                                    toread = icon_len - tot;
                                }
                                nread = Stream.Read(buffer_ICON, tot, toread);

                                if (nread == 0)
                                {
                                    Console.WriteLine("Connessione chiusa durante lettura");

                                    break;
                                }
                                tot += nread;
                            }
                            if (tot != icon_len)
                            {
                                Console.WriteLine("Read fallita: {0}", nread);
                                mainWindow.atClosingTime();
                            }

                            unsafe
                            {
                                fixed(byte *buffer = new byte[1048576])
                                {
                                    uint i = 0;

                                    foreach (byte item in buffer_ICON)
                                    {
                                        buffer[i++] = item;
                                    }
                                    IntPtr      Hicon  = CreateIconFromResourceEx((IntPtr)buffer, i, 1, 0x00030000, 48, 48, 0);
                                    BitmapFrame bitmap = BitmapFrame.Create(Imaging.CreateBitmapSourceFromHIcon(Hicon, new Int32Rect(0, 0, 48, 48), BitmapSizeOptions.FromEmptyOptions()));

                                    bitmap.Freeze();
                                    app.Icon = bitmap;
                                    DestroyIcon(Hicon);
                                }
                            }
                        }

                        // aggiunta nuova applicazione e notifica del cambiamento nella lista
                        lock (MainWindow._syncLock) {
                            mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                              new Action(() => { mainWindow.applications.Add(app); }));

                            mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                              new Action(() => {
                                mainWindow.listView_CollectionChanged(mainWindow.listView,
                                                                      new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, app));
                            }));
                        }

                        break;

                    case 1:
                        // Modifica REMOVE
                        Console.WriteLine("Modifica: Rimozione");

                        lock (MainWindow._syncLock) {
                            try {
                                foreach (ApplicationItem item in mainWindow.applications)
                                {
                                    if (item.PID == pid)
                                    {
                                        Console.WriteLine("Rimozione applicazione: {0}", item.Name);
                                        mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                          new Action(() => { mainWindow.applications.Remove(item); }));
                                        break;
                                    }
                                }
                            } catch (InvalidOperationException exc) {
                                Console.WriteLine("Exception: {0}", exc.Message);
                            }
                        }
                        break;

                    case 2:
                        //MODIFICA CHANGE FOCUS
                        Console.WriteLine("Modifica: Change Focus");

                        lock (MainWindow._syncLock) {
                            try {
                                foreach (ApplicationItem item in mainWindow.applications)
                                {
                                    if (item.PID == pid)
                                    {
                                        Console.WriteLine("Pid: {0} - applicazione: {1}", pid, item.Name);
                                        mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                          new Action(() => {
                                            item.IsFocused = true; mainWindow.listView.SelectedItem = item;
                                            int index      = mainWindow.foregroundApps.IndexOf(new ForegroundApp(item.Name, 0));
                                            if (index != -1)
                                            {
                                                mainWindow.foregroundApps[index].Count++;     //  Aggiornamento conteggio app
                                            }
                                            else
                                            {
                                                mainWindow.foregroundApps.Add(new ForegroundApp(item.Name, 1));
                                            }
                                        }));
                                    }
                                    else if (item.IsFocused)
                                    {
                                        Console.WriteLine("NO FOCUS-Pid: {0} - applicazione: {1}", item.PID, item.Name);
                                        mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                          new Action(() => {
                                            item.IsFocused = false;
                                            int index      = mainWindow.foregroundApps.IndexOf(new ForegroundApp(item.Name, 0));
                                            if (--mainWindow.foregroundApps[index].Count <= 0)
                                            {
                                                mainWindow.foregroundApps.RemoveAt(index);
                                            }
                                        }));
                                    }
                                }
                            } catch (InvalidOperationException exc) {
                                Console.WriteLine("Exception: {0}", exc.Message);
                            }
                        }
                        mainWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                          new Action(() => { mainWindow.percentageUpdate(null, null); }));
                        break;

                    default:
                        Console.WriteLine("Modifica sconosciuta");
                        break;
                    } //fine switch case
                }     // fine while
                Console.WriteLine("Thread - terminata ricezione dati dal server");
            } catch (NullReferenceException e) {
                Console.WriteLine("Exception message: {0}", e.Message);
            } catch (ThreadAbortException e) {
                /*TODO: da modificare/controllare*/
                Console.WriteLine("Thread - caught ThreadAbortException - resetting.");
                Console.WriteLine("Exception message: {0}", e.Message);
                Thread.ResetAbort();
            } catch (IOException e) {
                Console.WriteLine("Thread - caught IOException - connection closed");
                Console.WriteLine("Exception message: {0}", e.Message);
            }
        }