Archivo de la categoría: SomeCode

thread progressBar in WinForms – Also in C#

Después de una interesante conversación entorno a las diferencias de lenguaje “entre VB i C#” con mi amigo Jose María y de frente a la reiterativa discusión sobre la sintaxis… aquí os dejo el último ejemplo en C# para que lo comparéis con su anterior en VB.

Realmente pensáis que hay tanta diferencia como para continuar discutiendo cual mejor?, para poder apreciar los matices de cada uno de los lenguajes, como mínimo uno tiene que ser “bilingüe” y practicante pues en otro caso la discusión esta fuera de criterio…

El debate está servido! Jajajaja!. 

 

using System;
using System.Windows.Forms;
using System.Threading;
 
namespace ThreadProgressBar
{
    public partial class frmMain : Form
    {
        System.Timers.Timer tmr = new System.Timers.Timer(1000);
        delegate void myDeleg(Form toClose);
        Form currentPrgBar = null;
        Boolean createPrgBar = false;
        Boolean disposePrgBar = false;
 
        public frmMain()
        {
            InitializeComponent();
        }
 
        /// When form load
        private void frmMain_Load(object sender, EventArgs e)
        {
            tmr.Elapsed += tmr_Elapsed;
            tmr.Interval = 100;
            tmr.Start();
        }
 
        /// When running button is presed
        private void simulateLoad(object sender, EventArgs e)
        {
            createPrgBar = true;
            btnRunning.Text = "Load in progress";
            for (int i = 0; i < 10000; i++)
            {
                btnRunning.Text = "Running loop :" + i.ToString();
                btnRunning.Refresh();
                Application.DoEvents();
            }
            btnRunning.Text = "Run New Loop";
            disposePrgBar = true;
        }
 
        /// watch if any process are running to create a new progress bar
        void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (createPrgBar & (currentPrgBar == null))
            {
                Thread myThread = new Thread(onFlyProgressBar);
                myThread.Start();
                createPrgBar = false;
            }
            else
            {
                if (disposePrgBar)
                {
                    closeForm(currentPrgBar);
                    disposePrgBar = false;
                }
            }
        }
 
        /// Create new 'processing' progressBar
        void onFlyProgressBar()
        {
            Label lblMessage = new Label 
            {
                Dock = DockStyle.Top,
                Text = "Procesing, please wait..",
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Font = new System.Drawing.Font("Microsoft Sans Serif"14,
                                                System.Drawing.FontStyle.Bold,
                                                System.Drawing.GraphicsUnit.Point)                                                
            };
 
            ProgressBar prgBar = new ProgressBar
            {
                Height = 15,
                Dock = DockStyle.Bottom,
                Style = ProgressBarStyle.Marquee
            };
 
            currentPrgBar = new Form()
            {         
                Width = 300, Height = 50,
                StartPosition = FormStartPosition.CenterScreen,
                ControlBox = false,
                FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
            };
            currentPrgBar.Controls.AddRange(new Control[] { lblMessage, prgBar });
            currentPrgBar.LostFocus += recoverFocus;
            Application.Run(currentPrgBar);
        }
 
        void recoverFocus(object sender, EventArgs e)
        {
            currentPrgBar.TopMost = true;
        }
 
        /// Make current prgBar topmost if lost focus
        void closeForm(Form toClose)
        {
            if (toClose == nullreturn;
            if (toClose.InvokeRequired)
            {
                toClose.Invoke(new myDeleg(closeForm), toClose);
            }
            else
            {
                toClose.Close();
                currentPrgBar = null;
            }
        }
    }
}


Que tengáis una excelente semana!
PepLluis,

thread progressBar in WinForms

En el último post y en “WinForms”, comentamos como en algunas circunstancias se nos produce una excepción de ‘Subproceso Anulado’ cuando creamos/destruimos hilos en una misma función.

Después de conversar sobre el tema, y hablando con uno de vosotros sobre un escenario donde en ‘WinForm’ clásico nunca ha sido capaz de visualizar una ‘progress bar’ independientemente del form principal y aun pensando que deben existir montón de ejemplos J me he decidido a juguetear un ratito para ver como lo haría yo…

Este es el resultado (no sé si muy bueno, pero funciona.)

De todas maneras se me ocurre, que en próximos post podríamos hablar de cómo hacerlo usando “async”  “await” y “task”. Que os parece?

Si lo consideráis interesante no dudéis pedirme el equivalente en C#.

In the last post we are discussing around «WinForms» and some exceptions when create / destroy threads inside the same function.

After talking more about this, and share with somebody of you who are using classic ‘WinForm’ and has never been able to display a ‘progress bar’ independently of the main form, I think that we can found a plenty of examples on the web, But I decided tinkering for a while to see how I’d do it …

This is the result (not sure if is a very good sample, but it works.)

Anyway, it occurs to me that in next post could talk about how to do it using «async» «await» and «task». What you think?

Do not hesitate to ask me for the equivalent code in C #.

Espero vuestros comentarios!

Imports System.Threading
Public Class Main
 
    Private WithEvents tmr As New System.Timers.Timer(1000)
    Private currentPrgBar As Form
    Private createPrgBar As Boolean = False
    Private disposePrgBar As Boolean = False
 
    Delegate Sub myDeleg(toClose As Form)
 
    ''' When running button is presed
    Private Sub simulateLoad(sender As Object, e As EventArgsHandles btnRunning.Click
        createPrgBar = True
        btnRunning.Text = "Load in progress"
        For index = 1 To 10000
            btnRunning.Text = "Running loop :" + index.ToString
            btnRunning.Refresh()
            Application.DoEvents()
        Next
        btnRunning.Text = "Run New loop"
        disposePrgBar = True
    End Sub
 
    ''' watch if any process are running to create a new progress bar
    Private Sub tmr_Tick(sender As Object, e As EventArgsHandles tmr.Elapsed
        If createPrgBar And (currentPrgBar Is NothingThen
            Dim myThread As New Thread(AddressOf onFlyStatusBarForm)
            myThread.Start()
            createPrgBar = False
        Else
            If disposePrgBar Then
                closeForm(currentPrgBar)
                disposePrgBar = False
            End If
        End If
    End Sub
    ''' When form load
    Private Sub Main_Load(sender As Object, e As EventArgsHandles MyBase.Load
        tmr.Interval = 100
        tmr.Start()
    End Sub
    ''' When main form closes
    Private Sub Main_FormClosing(sender As Object, e As FormClosingEventArgsHandles MyBase.FormClosing
        closeForm(currentPrgBar)
    End Sub
 
    ''' Create new 'processing' progressBar
    Sub onFlyStatusBarForm()
        Dim lblMessage As New Label With {.Dock = DockStyle.Top,
                                          .Text = "Procesing, please wait..",
                                          .TextAlign = ContentAlignment.MiddleCenter,
                                          .Font = New System.Drawing.Font("Microsoft Sans Serif"14.0!,
                                                                          System.Drawing.FontStyle.Bold,
                                                                          System.Drawing.GraphicsUnit.Point,
                                                                          CType(0Byte))
                                         }
        Dim prgBar As New ProgressBar With {.Height = 15, .Dock = DockStyle.Bottom, .Style = ProgressBarStyle.Marquee}
 
        currentPrgBar = New Form() With {.Width = 300, .Height = 50,
                               .StartPosition = FormStartPosition.CenterScreen,
                               .ControlBox = False,
                               .FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
                              }
 
        currentPrgBar.Controls.AddRange(New Control() {lblMessage, prgBar})
        AddHandler currentPrgBar.LostFocus, AddressOf recoverFocus
        Application.Run(currentPrgBar)
    End Sub
 
    ''' Make current prgBar topmost if lost focus
    Private Sub recoverFocus(sender As Object, e As EventArgs)
        currentPrgBar.TopMost = True
    End Sub
 
    ''' Close current 'progressBar'
    Sub closeForm(toClose As Form)
        If toClose Is Nothing Then Exit Sub
        If toClose.InvokeRequired Then
            toClose.Invoke(New myDeleg(AddressOf closeForm), toClose)
        Else
            toClose.Close()
            currentPrgBar = Nothing
        End If
    End Sub
 
End Class

The Barcelona Developers Conference is back!

Este fin de semana, se celebra la BcnConDev de este 2013, además de una excelente zona «retro» disponemos de una sensacional área para «Robotics» y markers.

Segunda convocatoria 🙂 Si aun no conoces la «GadgetoMania»… vente mañana a la Design Hub de la plaza de las glorias en Barcelona y trastea con un montón de gadgets que traeré conmigo para que podamos montarnos algún que  otro desafío, por supuesto con la ayuda de nuestro portátil y visual Studio.

Por de pronto… a primera hora de la mañana nos las compondremos para mover a nuestro «carricoche» particular con los sensores de una Surface o de un Wndows Phone… si te mola, te estaremos esperando!

 

Y para que no falte, un poco de código que resuelve la comunicación y asi puedas concentrarte en la parte de los sensores.

        private TcpListener _listener;
        private Thread _listenerThread;
        private void StartListener()
        {
            _listenerThread = new Thread(RunListener);
            _listenerThread.Start();
        } 

        TcpClient client;
        private void RunListener()
        {
            _listener = new TcpListener(new IPAddress(new byte[] {192,168,1,101}), 5150);
            _listener.Start(); 
            while (true)
            {
                client = _listener.AcceptTcpClient();
                this.Invoke(
                    new Action(
                        () =>
                        {
                            // string.Format(«Nueva Conexion desde {0} \n\r», client.Client.RemoteEndPoint);
                        }
                    )); ;
                ThreadPool.QueueUserWorkItem(ProcessClient, client);
            }
        } 

        private void ProcessClient(object state)
        {
            TcpClient client = state as TcpClient;
        } 

        void Panic(object sender, EventArgs e)
        {
            sendStream(Encoding.ASCII.GetBytes(«/panic»));
        } 

        private void Atras(object sender, EventArgs e)
        {
            sendStream(Encoding.ASCII.GetBytes(«/backward»));
        } 

        private void Adelante(object sender, EventArgs e)
        {
            sendStream(Encoding.ASCII.GetBytes(«/forward»));
        } 

        void sendStream(byte[] bytes)
        {
            NetworkStream stream = client.GetStream();
            stream.Write(bytes, 0, bytes.Length);
        }

Hasta Mañana!!
PepLluis,

Team Fundation Services

 Know the Team Foundation Services!

A plan free for up to 5 users is now available! This service is a benefit of certain MSDN subscriptions at no additional charge.
Read more in Team Fundation Service

 Conozca los servicios de Team Foundationya está disponible un plan gratuito para un máximo de 5 usuarios!

Este servicio
 sin costo adicionales son una ventaja en determinadas suscripciones a MSDN.
Leer mas en Team Fundation Service

Espero te sea util!
PepLluis,

 

Como hacer transparente el fondo de nuestro PictureBox

Un Corto!

En determinadas ocasiones nos interesa que el fondo de nuestro PictureBox sea transparente…. sin olvidar que deberemos fijar un color de fondo homogenio para que termine siendo transparente.

Una vez tengamos la imagen cargada en el PictureBox

        Dim mibmp As Bitmap = PictureBox.Image
        Dim micol As Color = mibmp.GetPixel(1, 1)
        mibmp.MakeTransparent(micol)
        PictureBox.Image = mibmp

Facil no?
Saludos,

VB Gadgeteer Webserver, SDK 4.2 QFE2 and Spider Premium Library’s

This is an small sample code to show how to build our basic gadgeteer web server using VB with Spider and the 4.2 RTM Premium library’s.
Start Visual Studio with a new gadgeteer project and copy/paste…That’s all! (remember add library’s references)

Imports System.Net
Imports System.Text
Imports Microsoft.SPOT.Hardware
 
Imports GHI.Premium.Net
 
Imports GT = Gadgeteer
 
Partial Public Class Program
 
    Private WithEvents ethernet As New EthernetBuiltIn()
    
    Private ip As New IPAddress(New Byte() {0, 0, 0, 0})
    Private WithEvents myweb As WebEvent
    '
    Private WithEvents timer As GT.Timer = New GT.Timer(1000)
 
    Public Sub ProgramStarted()
        'Initialize adapter
        ethernet.Open()
        ethernet.NetworkInterface.EnableDhcp()
        ethernet.NetworkInterface.EnableDynamicDns()
        NetworkInterfaceExtension.AssignNetworkingStackTo(ethernet)
        'app timer on
        timer.Start()
    End Sub
 
    Private Sub ethernet_CableConnectivityChanged(sender As Object, e As GHI.Premium.Net.EthernetBuiltIn.CableConnectivityEventArgsHandles ethernet.CableConnectivityChanged
        If e.IsConnected Then
            ' reboot device after plug... to startup again
            PowerState.RebootDevice(True)
        End If
    End Sub
 
    Private Sub ReceivedWebEventHandler(path As String, method As WebServer.HttpMethod, responder As ResponderHandles myweb.WebEventReceived
        ' webb response
        responder.Respond(New System.Text.UTF8Encoding().GetBytes("Hello from " + ip.ToString() + " At " + System.DateTime.Now.ToString()), "text/html")
    End Sub
 
    Private tic As Boolean
    Private Sub timer_Tick(timer As Gadgeteer.TimerHandles timer.Tick
        ' blink debug led... system working
        tic = Not tic
        Mainboard.SetDebugLED(tic)
        ' get an IP from DHCP if no previous one
        If (ip.ToString = "0.0.0.0"And ethernet.IsCableConnected Then
            ip = IPAddress.GetDefaultLocalAddress()
            WebServer.StartLocalServer(ip.ToString(), 80)
            myweb = WebServer.SetupWebEvent("Hello")
        End If
    End Sub
End Class

Regards,
PepLluis,