6561
Sistemas Operativos / Windows / Re: Duda windows 8
en: 2 Octubre 2014, 20:57 pm
quiero saber si al pasarme a windows 8 ¿me podría valer?
Claro Senior++, no te preocupes por eso, VisualStudio 2013 es compatible con Windows 8/8.1, yo lo uso en dicho SO.
Saludos
6562
Sistemas Operativos / Windows / Re: Solucionar ruta demasiado larga en Windows al instalar un programa
en: 2 Octubre 2014, 19:05 pm
No puedes bypassear un límite que está impuesto en sl SO, un límite en la máquina, ciertas cosas se pueden llevar a cabo, pero otras simplemente
NO , tienes que adaptarte a dichas limitaciones.
Una posible alternativa para solucionar el problema podría ser modificando el nombre de usuario de tu perfil en caso de ser un nombre bastante largo, esto NO se hace de manera manual renombrando la carpeta... no vayas a intentarlo, y en fín, como resultado se modificaría el nombre de la carpeta
C:\Users\TuNombre\ la cual es necesaría para acceder a '
AppData ', pero antes de modificar el nombre mide la longitud de caracteres de la ruta completa, no vaya a servir para nada xD.
También podrías crear un nuevo usuario con un nombre muy corto, instalar el software en esa sesión, y luego acceder al software desde tu otra sesión de usuario.
De todas formas el error
1603 no tiene pinta de referirse a un error por nombre demasiado largo y aquí puedes encontrar posibles soluciones, síguelas al pie de la letra:
⇲ .NET 4 installation fails with error code 1603 ⇲ Error on AutoCAD 2014 1603 .NET Framework Runtime 4.0 Suerte!
6563
Sistemas Operativos / Windows / Re: CAMBIAR POSICION EN INICIO DEL PROGRAMA
en: 2 Octubre 2014, 18:40 pm
No entendiste bien el funcionamiento @FCOSTA, te explico:
1) No es una aplicación gráfica, es una aplicación commandline, es decir, se ejecuta desde la consola con los parámetros que ya indiqué más arriba:
Método de empleo:
SetWindowPos.exe "Nombre del proceso.exe" 2) La aplicación busca el programa entre los procesos activos, no es necesario mover el archivo a la misma carpeta, simplemente asegúrate que el proceso esté en ejecución, como ya indiqué: Primero ejecutas el "notepad" (notepad, por decir algo) y luego la aplicación que te envié.
3) No le añadí al código ningúna verificación de errores que te pueda indicar si hubo algún error (como por ejemplo si el proceso no se encontró), esto es porque no lo he desarrollado de forma profesional debido a que no lo vi necesario, solo le añadí un par de instruccines básicas para que tomase el argumento que le debes enviar por consola para que te funcionase, nada más.
Asegúrate de utilizarla como es debido y todo debería ir bien
EDITO: Un ejemplo Visual:
VIDEO ¿Lo entendiste ahora?, en pocas palabras, úsalo como si se tratase de un comando de Batch al que le pasas un parámetro, del mismo modo,
La idea es que ejecutes esa aplicación al mismo tiempo que ejecutas la aplicación que quieres mover, supongo que lo haces al inicio de Windows, pues eso, solo tienes que añadir una entrada más a la sección 'RUN' donde se define la ejecución de esos programas.
Ejemplo:
Windows Registry Editor Version 5.00
[ HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]
"SetWindowPos" = "\" C:\\SetWindowPos.exe\" \" Nombre del Programa.exe\""
PD: Si sigues teniendo dificultades enviame el exe del programa que se pone en medio de la pantalla (y sus dependencias si tiene alguna para poder ejecutarlo) y te hago un apaño.
Saludos!
6564
Sistemas Operativos / Windows / Re: Duda windows 8
en: 2 Octubre 2014, 18:28 pm
1. Tengo actualmente el sistema operativo Windows 7 ¿Merece la pena quitarme de windows 7 para probar windows 8?
Soy un amante de Windows 7, desde que lo instalé por primera vez lo empecé a considerar el mejor SO de Windows, pero eso cambió cuando me actualicé a Windows 8/8.1, ¿eso te da una idea?, pero de todas formas, y para que mi opinión no se base solo en gustos personales, es sabido que las diferencias técnicas de Windows 7 a Windows 8 son abismales. empezando por un mayor rendimiento y estabilidad, y una mayor seguridad, tienes mucha información en internet, análisis comparativos, tablas de diferencias, no veo suficiente motivo para formular esa pregunta ya que en Google puedes encontrar la respuesta, y siempre será la misma
.
2. ¿Que Windows 8 me aconsejan? Simplemente lo quiero para PROGRAMAR y de juego simplemente league of legends
Yo también soy programador, y también juego a MMORPGS, uso la versión Core de Windows 8.1 (es decir, la edición normal) y esa es la que yo te sugiero, no importa mucho si te instalas la Core o la Pro, pero no subas más cuesta arriba porque te estarías instalando por defecto muchas características que no vas a utilizar en la vida (pero que tu sistema las activará dia a día disminuyendo el rendimiento general de tu PC), hazme caso, ¡es un consejo!.
Te instales la que te instales, recuerda realizar siempre una limpieza general de servicios después de la instalación para evitar toda esa basura innecesaria que Windows te instala por defecto. PD: La versión Core se distribuye en el mismo DVD que la versión Pro, dependiendo del Serial que utilices se te instala una edición u otra.
3. ¿Que ventajas podría tener con windows 8 que con el 7 no?
Eso es algo a lo que sinceramente no me apetece responder por el motivo que ya comenté en la primera cita, y porque se ha discutido cientos d evecs en el foro... puedes utilizar el buscador del foro al menos, y además, seguro que se me escaparian algunas ventajas importantes al nombrarlas, tienes toda la información a tu disposición en la Web:
http://lmgtfy.com/?q=Windows+8+advantages ¿ Cuando instale windows 8 debo de tener algo en cuenta? es decir, ¿problemas de instalación?
Si tu PC es de serie e indica que soporta Windows 8 perfectamente entonces no deberías preocuparte mucho, por otro lado, se conocen problemas de instalación con algunos dispositivos de Hardware, además y sobretodo he leido muchisimos problemas de instalación defectuosa al intentar actualizar desde Windows 7 a Windows 8/8.1, o reemplazar el sistema, yo lo hice y no tuve problema alguno, en mi opinión, nunca se sabe si algo puede fallar a la hora de la verdad al instalar un SO... y tampoco si el usuario puede estar involucrado en el problema y que realmente no sea culpa de Windows, pero si quieres evitar este tipo de problema, realiza una instalación limpia de Windows cuandolo instales, es decir,
NO hagas una actualización sel SO para preservar la configuración del software que tienes instalado y etc...
Saludos!
6566
Foros Generales / Sugerencias y dudas sobre el Foro / Re: Exigir/obligar a los usuarios del foro escribir de forma correcta
en: 2 Octubre 2014, 07:39 am
@Engel Lex, no creas que alguien tiene mérito por acertarlas todas, cualquiera puede hacerlo, la verdad es que es un juego muy pero que muy sencillo, yo lo considero for dummies , la mayoría de las palabras están pensadas para confundir a gente extrajera que sisea, esas palabras son las más faciles para los Españoles (ya que conocemos y respetamos el Castellano xD), yo fallé en la palabra "huso", reconozco que ni siquiera conocia esa palabra o se me olvidó con el paso de los años, el resto ha sido pan comido. Saludos!
6567
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets)
en: 2 Octubre 2014, 06:39 am
Modifica el estado de una ventana.
' ***********************************************************************
' Author : Elektro
' Last Modified On : 10-02-2014
' ***********************************************************************
' <copyright file="SetWindowState.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Usage Examples "
'Dim HWND As IntPtr = Process.GetProcessesByName("devenv").First.MainWindowHandle
'
'SetWindowState.SetWindowState(HWND, SetWindowState.WindowState.Hide)
'SetWindowState.SetWindowState("devenv", SetWindowState.WindowState.Restore, Recursivity:=False)
#End Region
#Region " Imports "
Imports System.Runtime .InteropServices
#End Region
''' <summary>
''' Sets the state of a window.
''' </summary>
Public NotInheritable Class SetWindowState
#Region " P/Invoke "
''' <summary>
''' Platform Invocation methods (P/Invoke), access unmanaged code.
''' This class does not suppress stack walks for unmanaged code permission.
''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
''' This class is for methods that can be used anywhere because a stack walk will be performed.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
''' </summary>
Protected NotInheritable Class NativeMethods
#Region " Methods "
''' <summary>
''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
''' This function does not search child windows.
''' This function does not perform a case-sensitive search.
''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
''' </summary>
''' <param name="lpClassName">The class name.
''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
''' <param name="lpWindowName">The window name (the window's title).
''' If this parameter is NULL, all window names match.</param>
''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
''' If the function fails, the return value is NULL.</returns>
<DllImport( "user32.dll" , SetLastError:= False , CharSet:= CharSet.Auto , BestFitMapping:= False ) >
Friend Shared Function FindWindow(
ByVal lpClassName As String ,
ByVal lpWindowName As String
) As IntPtr
End Function
''' <summary>
''' Retrieves a handle to a window whose class name and window name match the specified strings.
''' The function searches child windows, beginning with the one following the specified child window.
''' This function does not perform a case-sensitive search.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633500%28v=vs.85%29.aspx
''' </summary>
''' <param name="hwndParent">
''' A handle to the parent window whose child windows are to be searched.
''' If hwndParent is NULL, the function uses the desktop window as the parent window.
''' The function searches among windows that are child windows of the desktop.
''' </param>
''' <param name="hwndChildAfter">
''' A handle to a child window.
''' The search begins with the next child window in the Z order.
''' The child window must be a direct child window of hwndParent, not just a descendant window.
''' If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.
''' </param>
''' <param name="strClassName">
''' The window class name.
''' </param>
''' <param name="strWindowName">
''' The window name (the window's title).
''' If this parameter is NULL, all window names match.
''' </param>
''' <returns>
''' If the function succeeds, the return value is a handle to the window that has the specified class and window names.
''' If the function fails, the return value is NULL.
''' </returns>
<DllImport( "User32.dll" , SetLastError:= False , CharSet:= CharSet.Auto , BestFitMapping:= False ) >
Friend Shared Function FindWindowEx(
ByVal hwndParent As IntPtr,
ByVal hwndChildAfter As IntPtr,
ByVal strClassName As String ,
ByVal strWindowName As String
) As IntPtr
End Function
''' <summary>
''' Retrieves the identifier of the thread that created the specified window
''' and, optionally, the identifier of the process that created the window.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx
''' </summary>
''' <param name="hWnd">A handle to the window.</param>
''' <param name="ProcessId">
''' A pointer to a variable that receives the process identifier.
''' If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable;
''' otherwise, it does not.
''' </param>
''' <returns>The identifier of the thread that created the window.</returns>
<DllImport( "user32.dll" ) >
Friend Shared Function GetWindowThreadProcessId(
ByVal hWnd As IntPtr,
ByRef ProcessId As Integer
) As Integer
End Function
''' <summary>
''' Sets the specified window's show state.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
''' </summary>
''' <param name="hwnd">A handle to the window.</param>
''' <param name="nCmdShow">Controls how the window is to be shown.</param>
''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
<DllImport( "User32" , SetLastError:= False ) >
Friend Shared Function ShowWindow(
ByVal hwnd As IntPtr,
ByVal nCmdShow As WindowState
) As Boolean
End Function
#End Region
End Class
#End Region
#Region " Enumerations "
''' <summary>
''' Controls how the window is to be shown.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
''' </summary>
Friend Enum WindowState As Integer
''' <summary>
''' Hides the window and activates another window.
''' </summary>
Hide = 0I
''' <summary>
''' Activates and displays a window.
''' If the window is minimized or maximized, the system restores it to its original size and position.
''' An application should specify this flag when displaying the window for the first time.
''' </summary>
Normal = 1I
''' <summary>
''' Activates the window and displays it as a minimized window.
''' </summary>
ShowMinimized = 2I
''' <summary>
''' Maximizes the specified window.
''' </summary>
Maximize = 3I
''' <summary>
''' Activates the window and displays it as a maximized window.
''' </summary>
ShowMaximized = Maximize
''' <summary>
''' Displays a window in its most recent size and position.
''' This value is similar to <see cref="WindowState.Normal"/>, except the window is not actived.
''' </summary>
ShowNoActivate = 4I
''' <summary>
''' Activates the window and displays it in its current size and position.
''' </summary>
Show = 5I
''' <summary>
''' Minimizes the specified window and activates the next top-level window in the Z order.
''' </summary>
Minimize = 6I
''' <summary>
''' Displays the window as a minimized window.
''' This value is similar to <see cref="WindowState.ShowMinimized"/>, except the window is not activated.
''' </summary>
ShowMinNoActive = 7I
''' <summary>
''' Displays the window in its current size and position.
''' This value is similar to <see cref="WindowState.Show"/>, except the window is not activated.
''' </summary>
ShowNA = 8I
''' <summary>
''' Activates and displays the window.
''' If the window is minimized or maximized, the system restores it to its original size and position.
''' An application should specify this flag when restoring a minimized window.
''' </summary>
Restore = 9I
''' <summary>
''' Sets the show state based on the SW_* value specified in the STARTUPINFO structure
''' passed to the CreateProcess function by the program that started the application.
''' </summary>
ShowDefault = 10I
''' <summary>
''' <b>Windows 2000/XP:</b>
''' Minimizes a window, even if the thread that owns the window is not responding.
''' This flag should only be used when minimizing windows from a different thread.
''' </summary>
ForceMinimize = 11I
End Enum
#End Region
#Region " Public Methods "
''' <summary>
''' Set the state of a window by an HWND.
''' </summary>
''' <param name="WindowHandle">A handle to the window.</param>
''' <param name="WindowState">The state of the window.</param>
''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
Friend Shared Function SetWindowState( ByVal WindowHandle As IntPtr,
ByVal WindowState As WindowState) As Boolean
Return NativeMethods.ShowWindow ( WindowHandle, WindowState)
End Function
''' <summary>
''' Set the state of a window by a process name.
''' </summary>
''' <param name="ProcessName">The name of the process.</param>
''' <param name="WindowState">The state of the window.</param>
''' <param name="Recursivity">If set to <c>false</c>, only the first process instance will be processed.</param>
Friend Shared Sub SetWindowState( ByVal ProcessName As String ,
ByVal WindowState As WindowState,
Optional ByVal Recursivity As Boolean = False )
If ProcessName.EndsWith ( ".exe" , StringComparison.OrdinalIgnoreCase ) Then
ProcessName = ProcessName.Remove ( ProcessName.Length - ".exe" .Length )
End If
Dim pHandle As IntPtr = IntPtr.Zero
Dim pID As Integer = 0I
Dim Processes As Process( ) = Process.GetProcessesByName ( ProcessName)
' If any process matching the name is found then...
If Processes.Count = 0 Then
Exit Sub
End If
For Each p As Process In Processes
' If Window is visible then...
If p.MainWindowHandle <> IntPtr.Zero Then
SetWindowState( p.MainWindowHandle , WindowState)
Else ' Window is hidden
' Check all open windows (not only the process we are looking),
' begining from the child of the desktop, phandle = IntPtr.Zero initialy.
While pID <> p.Id ' Check all windows.
' Get child handle of window who's handle is "pHandle".
pHandle = NativeMethods.FindWindowEx ( IntPtr.Zero , pHandle, Nothing , Nothing )
' Get ProcessId from "pHandle".
NativeMethods.GetWindowThreadProcessId ( pHandle, pID)
' If the ProcessId matches the "pID" then...
If pID = p.Id Then
NativeMethods.ShowWindow ( pHandle, WindowState)
If Not Recursivity Then
Exit For
End If
End If
End While
End If
Next p
End Sub
#End Region
End Class
6568
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets)
en: 2 Octubre 2014, 06:31 am
Ejemplo de como crear una propiedad con un rango asignado...
Public Class MyType
''' <summary>
''' Gets or sets the value.
''' </summary>
''' <value>The value.</value>
Public Property MyProperty As Integer
Get
Return Me ._MyValue
End Get
Set ( ByVal value As Integer )
If value < Me ._MyValueMin Then
If Me ._MyValueThrowRangeException Then
Throw New ArgumentOutOfRangeException( "MyValue" , Me ._MyValueExceptionMessage)
End If
Me ._MyValue = Me ._MyValueMin
ElseIf value > Me ._MyValueMax Then
If Me ._MyValueThrowRangeException Then
Throw New ArgumentOutOfRangeException( "MyValue" , Me ._MyValueExceptionMessage)
End If
Me ._MyValue = Me ._MyValueMax
Else
Me ._MyValue = value
End If
End Set
End Property
Private _MyValue As Integer = 0I
Private _MyValueMin As Integer = 0I
Private _MyValueMax As Integer = 10I
Private _MyValueThrowRangeException As Boolean = True
Private _MyValueExceptionMessage As String = String .Format ( "The valid range is beetwen {0} and {1}" ,
Me ._MyValueMin, Me ._MyValueMax)
End Class
Una utilidad para mostrar, ocultar, o intercambiar el estado del escritorio.
Nota: El método ToggleDesktop no funciona en WinXP.
' ***********************************************************************
' Author : Elektro
' Last Modified On : 09-23-2014
' ***********************************************************************
' <copyright file="DesktopVisibility.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Usage Examples "
' DesktopVisibility.ShowDesktop()
' DesktopVisibility.HideDesktop()
' DesktopVisibility.ToggleDesktop()
#End Region
#Region " Imports "
Imports System.Runtime .InteropServices
#End Region
#Region " DesktopVisibility "
''' <summary>
''' Shows, hides, or toggles the desktop.
''' </summary>
Public NotInheritable Class DesktopVisibility
#Region " Objects "
''' <summary>
''' "Shell" CLASSID.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776890%28v=vs.85%29.aspx
''' </summary>
Private Shared ReadOnly CLSIDShell As New Guid( "13709620-C279-11CE-A49E-444553540000" )
''' <summary>
''' Gets the objects in the Shell.
''' Methods are provided to control the Shell and to execute commands within the Shell.
''' There are also methods to obtain other Shell-related objects.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb774094%28v=vs.85%29.aspx
''' </summary>
Private Shared ReadOnly Property Shell As Object
Get
If _Shell Is Nothing Then
_Shell = Activator.CreateInstance ( Type.GetTypeFromCLSID ( CLSIDShell) )
Return _Shell
Else
Return _Shell
End If
End Get
End Property
Private Shared _Shell As Object = Nothing
#End Region
#Region " P/Invoke "
#Region " Methods "
''' <summary>
''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
''' This function does not search child windows.
''' This function does not perform a case-sensitive search.
''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
''' </summary>
''' <param name="lpClassName">The class name.
''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
''' <param name="lpWindowName">The window name (the window's title).
''' If this parameter is NULL, all window names match.</param>
''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
''' If the function fails, the return value is NULL.</returns>
<DllImport( "user32.dll" , SetLastError:= False ) >
Private Shared Function FindWindow(
ByVal lpClassName As String ,
ByVal lpWindowName As String
) As IntPtr
End Function
''' <summary>
''' Sends the specified message to a window or windows.
''' The SendMessage function calls the window procedure for the specified window
''' and does not return until the window procedure has processed the message.
''' </summary>
''' <param name="hWnd">A handle to the window whose window procedure will receive the message.</param>
''' <param name="Msg">The message to be sent.</param>
''' <param name="wParam">Additional message-specific information.</param>
''' <param name="lParam">Additional message-specific information.</param>
''' <returns>IntPtr.</returns>
<DllImport( "user32.dll" , SetLastError:= False ) >
Private Shared Function SendMessage(
ByVal hWnd As IntPtr,
ByVal Msg As WindowsMessages,
ByVal wParam As IntPtr,
ByVal lParam As IntPtr
) As IntPtr
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' Specifies a System-Defined Message.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927%28v=vs.85%29.aspx#system_defined
''' </summary>
Public Enum WindowsMessages
''' <summary>
''' Message sent when the user selects a command item from a menu,
''' when a control sends a notification message to its parent window,
''' or when an accelerator keystroke is translated.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms647591%28v=vs.85%29.aspx
''' </summary>
WM_COMMAND = & H111UI
End Enum
#End Region
#Region " Constants "
''' <summary>
''' Minimize all windows.
''' </summary>
Const MIN_ALL As Integer = 419
''' <summary>
''' Undo the minimization of all minimized windows.
''' </summary>
Const MIN_ALL_UNDO As Integer = 416
#End Region
#End Region
#Region " Public Methods "
''' <summary>
''' Shows the desktop.
''' </summary>
Public Shared Sub ShowDesktop( )
SendMessage( FindWindow( "Shell_TrayWnd" , Nothing ) ,
WindowsMessages.WM_COMMAND ,
New IntPtr( MIN_ALL) , IntPtr.Zero )
End Sub
''' <summary>
''' Hides the desktop.
''' </summary>
Public Shared Sub HideDesktop( )
SendMessage( FindWindow( "Shell_TrayWnd" , Nothing ) ,
WindowsMessages.WM_COMMAND ,
New IntPtr( MIN_ALL_UNDO) , IntPtr.Zero )
End Sub
''' <summary>
''' Shows or hides the desktop.
''' </summary>
Public Shared Sub ToggleDesktop( )
Shell .ToggleDesktop ( ) ' Doesns't works in Windows XP
End Sub
#End Region
End Class
#End Region
Utilidad para posicionar una ventana en la pantalla, se puede elegir una de las posiciones predeterminadas (las esquinas de la pantalla) o especificar unas coordenadas exactas.
' ***********************************************************************
' Author : Elektro
' Last Modified On : 10-01-2014
' ***********************************************************************
' <copyright file="SetWindowPosition.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Example Usage "
' SetWindowPosition.SetWindowPos("proceso.exe", SetWindowPosition.Corner.BottomRight)
' SetWindowPosition.SetWindowPos("proceso.exe", X:=100, Y:=100, Bounds:=SystemInformation.VirtualScreen)
#End Region
#Region " Imports "
Imports System.ComponentModel
Imports System.Runtime .InteropServices
#End Region
''' <summary>
''' Set the position of a window.
''' </summary>
Public Class SetWindowPosition
#Region " P/Invoke "
''' <summary>
''' Platform Invocation methods (P/Invoke), access unmanaged code.
''' This class does not suppress stack walks for unmanaged code permission.
''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/> must not be applied to this class.
''' This class is for methods that can be used anywhere because a stack walk will be performed.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
''' </summary>
Protected NotInheritable Class NativeMethods
#Region " Methods "
''' <summary>
''' Changes the size, position, and Z order of a child, pop-up, or top-level window.
''' These windows are ordered according to their appearance on the screen.
''' The topmost window receives the highest rank and is the first window in the Z order.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
''' </summary>
''' <param name="hWnd">
''' A handle to the window.
''' </param>
''' <param name="hWndInsertAfter">
''' A special handle to the window to precede the positioned window in the Z order.
''' This parameter must be a window handle or one of the <see cref="SpecialWindowHandles"/> values.
''' </param>
''' <param name="X">
''' The new position of the left side of the window, in client coordinates.
''' </param>
''' <param name="Y">
''' The new position of the top of the window, in client coordinates.
''' </param>
''' <param name="cx">
''' The new width of the window, in pixels.
''' </param>
''' <param name="cy">
''' The new height of the window, in pixels.
''' </param>
''' <param name="uFlags">
''' The window sizing and positioning flags.
''' </param>
''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
<DllImport( "user32.dll" , SetLastError:= True ) >
Friend Shared Function SetWindowPos(
ByVal hWnd As IntPtr,
ByVal hWndInsertAfter As SpecialWindowHandles,
ByVal X As Integer ,
ByVal Y As Integer ,
ByVal cx As Integer ,
ByVal cy As Integer ,
ByVal uFlags As SetWindowPosFlags
) As Boolean
End Function
''' <summary>
''' Retrieves the dimensions of the bounding rectangle of the specified window.
''' The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633519%28v=vs.85%29.aspx
''' </summary>
''' <param name="hWnd">A handle to the window.</param>
''' <param name="rc">
''' A pointer to a RECT structure that receives the screen coordinates of
''' the upper-left and lower-right corners of the window.
''' </param>
''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
<DllImport( "user32.dll" , SetLastError:= True ) >
Friend Shared Function GetWindowRect(
ByVal hWnd As IntPtr,
ByRef rc As Rectangle
) As Boolean
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' Specifies the window sizing and positioning flags.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
''' </summary>
<Description( "Enum used as 'uFlags' parameter of 'NativeMethods.SetWindowPos' function" ) >
<Flags>
Friend Enum SetWindowPosFlags As UInteger
''' <summary>
''' If the calling thread and the thread that owns the window are attached to different input queues,
''' the system posts the request to the thread that owns the window.
''' This prevents the calling thread from blocking its execution while other threads process the request.
''' </summary>
''' <remarks>SWP_ASYNCWINDOWPOS</remarks>
SynchronousWindowPosition = & H4000UI
''' <summary>
''' Prevents generation of the WM_SYNCPAINT message.
''' </summary>
''' <remarks>SWP_DEFERERASE</remarks>
DeferErase = & H2000UI
''' <summary>
''' Draws a frame (defined in the window's class description) around the window.
''' </summary>
''' <remarks>SWP_DRAWFRAME</remarks>
DrawFrame = & H20UI
''' <summary>
''' Applies new frame styles set using the SetWindowLong function.
''' Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed.
''' If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
''' </summary>
''' <remarks>SWP_FRAMECHANGED</remarks>
FrameChanged = & H20UI
''' <summary>
''' Hides the window.
''' </summary>
''' <remarks>SWP_HIDEWINDOW</remarks>
HideWindow = & H80UI
''' <summary>
''' Does not activate the window.
''' If this flag is not set, the window is activated and moved to the top of
''' either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
''' </summary>
''' <remarks>SWP_NOACTIVATE</remarks>
DoNotActivate = & H10UI
''' <summary>
''' Discards the entire contents of the client area. If this flag is not specified,
''' the valid contents of the client area are saved and copied back into the
''' client area after the window is sized or repositioned.
''' </summary>
''' <remarks>SWP_NOCOPYBITS</remarks>
DoNotCopyBits = & H100UI
''' <summary>
''' Retains the current position (ignores X and Y parameters).
''' </summary>
''' <remarks>SWP_NOMOVE</remarks>
IgnoreMove = & H2UI
''' <summary>
''' Does not change the owner window's position in the Z order.
''' </summary>
''' <remarks>SWP_NOOWNERZORDER</remarks>
DoNotChangeOwnerZOrder = & H200UI
''' <summary>
''' Does not redraw changes.
''' If this flag is set, no repainting of any kind occurs.
''' This applies to the client area, the nonclient area (including the title bar and scroll bars),
''' and any part of the parent window uncovered as a result of the window being moved.
''' When this flag is set, the application must explicitly invalidate or
''' redraw any parts of the window and parent window that need redrawing.
''' </summary>
''' <remarks>SWP_NOREDRAW</remarks>
DoNotRedraw = & H8UI
''' <summary>
''' Same as the SWP_NOOWNERZORDER flag.
''' </summary>
''' <remarks>SWP_NOREPOSITION</remarks>
DoNotReposition = & H200UI
''' <summary>
''' Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
''' </summary>
''' <remarks>SWP_NOSENDCHANGING</remarks>
DoNotSendChangingEvent = & H400UI
''' <summary>
''' Retains the current size (ignores the cx and cy parameters).
''' </summary>
''' <remarks>SWP_NOSIZE</remarks>
IgnoreResize = & H1UI
''' <summary>
''' Retains the current Z order (ignores the hWndInsertAfter parameter).
''' </summary>
''' <remarks>SWP_NOZORDER</remarks>
IgnoreZOrder = & H4UI
''' <summary>
''' Displays the window.
''' </summary>
''' <remarks>SWP_SHOWWINDOW</remarks>
ShowWindow = & H40UI
End Enum
''' <summary>
''' Specifies a special handle to the window to precede the positioned window in the Z order.
''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
''' </summary>
<Description( "Enum used as 'hWndInsertAfter' parameter of 'NativeMethods.SetWindowPos' function" ) >
Friend Enum SpecialWindowHandles As Integer
''' <summary>
''' Places the window at the top of the Z order.
''' </summary>
Top = 0I
''' <summary>
''' Places the window at the bottom of the Z order.
''' If the hWnd parameter identifies a topmost window,
''' the window loses its topmost status and is placed at the bottom of all other windows.
''' </summary>
Bottom = 1I
''' <summary>
''' Places the window above all non-topmost windows.
''' The window maintains its topmost position even when it is deactivated.
''' </summary>
TopMost = - 1I
''' <summary>
''' Places the window above all non-topmost windows (that is, behind all topmost windows).
''' This flag has no effect if the window is already a non-topmost window.
''' </summary>
NoTopMost = - 2I
End Enum
#End Region
End Class
#End Region
#Region " Enumerations "
''' <summary>
''' Specifies a screen corner.
''' </summary>
<Description( "Enum used as 'Corner' parameter of 'SetWindowPos' function" ) >
Friend Enum Corner As Integer
''' <summary>
''' Top-Left screen corner.
''' </summary>
TopLeft = 0I
''' <summary>
''' Top-Right screen corner.
''' </summary>
TopRight = 1I
''' <summary>
''' Bottom-Left screen corner.
''' </summary>
BottomLeft = 2I
''' <summary>
''' Bottom-Right screen corner.
''' </summary>0
BottomRight = 3I
End Enum
#End Region
#Region " Public Methods "
''' <summary>
''' Set the position of a window.
''' </summary>
''' <param name="ProcessName">The process name.</param>
''' <param name="Corner">The new window position, a screen corner.</param>
''' <param name="Bounds">
''' The screen <see cref="Rectangle"/> where the window is shown.
''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
''' </param>
Friend Shared Sub SetWindowPos( ByVal ProcessName As String ,
ByVal Corner As Corner,
Optional ByVal Bounds As Rectangle = Nothing )
Dim Rect As Rectangle ' The specified screen bounds
Dim HWND As IntPtr ' The process main window handle.
Dim Width As Integer ' The process window width.
Dim Height As Integer ' The process window height.
Dim x As Integer
Dim y As Integer
If Bounds.IsEmpty Then
Bounds = Screen.PrimaryScreen .WorkingArea
End If
' Iterate the process instances.
For Each p As Process In Process.GetProcessesByName ( FixProcessName( ProcessName) )
Try
' Get the main window handle.
HWND = p.MainWindowHandle
' Copy the process window position and size into the Rectangle.
' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
NativeMethods.GetWindowRect ( HWND, Rect)
Width = ( Rect.Width - Rect.Left ) ' Set the window width
Height = ( Rect.Height - Rect.Top ) ' Set the window height
Select Case Corner
Case SetWindowPosition.Corner .TopLeft
x = Bounds.Left
y = Bounds.Top
Case SetWindowPosition.Corner .TopRight
x = Bounds.Right - Width
y = Bounds.Top
Case SetWindowPosition.Corner .BottomLeft
x = Bounds.Left
y = Bounds.Bottom - Height
Case SetWindowPosition.Corner .BottomRight
x = Bounds.Right - Width
y = Bounds.Bottom - Height
End Select
' Move the Main Window.
NativeMethods.SetWindowPos ( HWND, New IntPtr( NativeMethods.SpecialWindowHandles .NoTopMost ) ,
x, y, 0 , 0 ,
NativeMethods.SetWindowPosFlags .IgnoreResize )
Catch ex As Exception
Throw
End Try
Next
End Sub
''' <summary>
''' Set the position of a window.
''' </summary>
''' <param name="ProcessName">The process name.</param>
''' <param name="X">The new X coordinate.</param>
''' <param name="Y">The new Y coordinate.</param>
''' <param name="Bounds">
''' The screen <see cref="Rectangle"/> where the window is shown.
''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
''' </param>
Friend Shared Sub SetWindowPos( ByVal ProcessName As String ,
ByVal X As Integer ,
ByVal Y As Integer ,
Optional ByVal Bounds As Rectangle = Nothing )
Dim Rect As Rectangle ' The specified screen bounds
Dim HWND As IntPtr ' The process main window handle.
Dim Width As Integer ' The process window width.
Dim Height As Integer ' The process window height.
If Bounds.IsEmpty Then
Bounds = Screen.PrimaryScreen .WorkingArea
End If
' Iterate the process instances.
For Each p As Process In Process.GetProcessesByName ( FixProcessName( ProcessName) )
Try
' Get the main window handle.
HWND = p.MainWindowHandle
' Copy the process window position and size into the Rectangle.
' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
NativeMethods.GetWindowRect ( HWND, Rect)
Width = ( Rect.Width - Rect.Left ) ' Set the window width
Height = ( Rect.Height - Rect.Top ) ' Set the window height
' Move the Main Window.
NativeMethods.SetWindowPos ( HWND, New IntPtr( NativeMethods.SpecialWindowHandles .NoTopMost ) ,
x, y, 0 , 0 ,
NativeMethods.SetWindowPosFlags .IgnoreResize )
Catch ex As Exception
Throw
End Try
Next
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Fixes the name of a process.
''' </summary>
''' <param name="name">The process name.</param>
''' <returns>System.String.</returns>
Private Shared Function FixProcessName( ByVal name As String ) As String
If name.EndsWith ( ".exe" , StringComparison.OrdinalIgnoreCase ) Then
Return name.Remove ( name.Length - ".exe" .Length )
Else
Return name
End If
End Function
#End Region
End Class
Añade o elimina una aplicación de la sección 'Run' del registro, para iniciar una aplicación cuando el usuario se loguea en Windows.
' Add or remove application from Windows Startup
' ( By Elektro )
'
' Usage Examples :
' AddApplicationToWindowsStartup(User.CurrentUser, Application.ProductName, Application.ExecutablePath)
' RemoveApplicationFromWindowsStartup(User.CurrentUser, pplication.ProductName)
''' <summary>
''' Specifies a registry user session.
''' </summary>
Public Enum User As Integer
''' <summary>
''' The current user session.
''' </summary>
CurrentUser = 1I
''' <summary>
''' All user sessions.
''' </summary>
AllUsers = 2I
End Enum
''' <summary>
''' Adds an application to Windows Startup.
''' </summary>
''' <param name="User">Indicates the registry root key.</param>
''' <param name="Title">Indicates the registry value name.</param>
''' <param name="FilePath">Indicates the registry value data.</param>
Friend Shared Sub AddApplicationToWindowsStartup( ByVal User As User,
ByVal Title As String ,
ByVal FilePath As String )
Try
Select Case User
Case User.CurrentUser
My.Computer .Registry .CurrentUser .
OpenSubKey ( "Software\Microsoft\Windows\CurrentVersion\Run" , writable:= True ) .
SetValue ( Title, FilePath, Microsoft.Win32 .RegistryValueKind .String )
Case User.AllUsers
My.Computer .Registry .LocalMachine .
OpenSubKey ( "Software\Microsoft\Windows\CurrentVersion\Run" , writable:= True ) .
SetValue ( Title, FilePath, Microsoft.Win32 .RegistryValueKind .String )
Case Else
Exit Select
End Select
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' Removes an application from Windows Startup.
''' </summary>
''' <param name="User">Indicates the registry root key.</param>
''' <param name="Title">Indicates the registry value name.</param>
Friend Shared Sub RemoveApplicationFromWindowsStartup( ByVal User As User,
ByVal Title As String )
Try
Select Case User
Case User.CurrentUser
My.Computer .Registry .CurrentUser .
OpenSubKey ( "Software\Microsoft\Windows\CurrentVersion\Run" , writable:= True ) .
DeleteValue ( Title, throwOnMissingValue:= False )
Case User.AllUsers
My.Computer .Registry .LocalMachine .
OpenSubKey ( "Software\Microsoft\Windows\CurrentVersion\Run" , writable:= True ) .
DeleteValue ( Title, throwOnMissingValue:= False )
Case Else
Exit Select
End Select
Catch ex As Exception
Throw
End Try
End Sub
Obtiene la ruta de un proceso de 64 Bits, desde una aplicación .NET de 32 Bits.
Aviso, es un procedimiento lento, pero por el momento no conozco una mejor manera de lograrlo.
' Get x64 Process Path From x86
' ( By Elektro )
'
' Instructions:
' 1. Add a reference to 'System.Management'
'
' Usage Examples:
' Dim path As String = GetX64ProcessPathFromX86("conhost.exe")
'
''' <summary>
''' Gets the process path of an x64 process from an x86 .NET application.
''' </summary>
''' <param name="ProcessName">Indicates the name of the process.</param>
''' <returns>The process path.</returns>
Friend Shared Function GetX64ProcessPathFromX86( ByVal ProcessName As String ) As String
Dim wmiQuery As String = String .Format ( "SELECT ExecutablePath FROM Win32_Process Where Name = '{0}.exe'" ,
If ( ProcessName.EndsWith ( ".exe" , StringComparison.OrdinalIgnoreCase ) ,
ProcessName.Remove ( ProcessName.Length - ".exe" .Length ) ,
ProcessName) )
Using searcher As New ManagementObjectSearcher( queryString:= wmiQuery)
Using results As ManagementObjectCollection = searcher.[ Get ]
If results.Count <> 0I Then
Return DirectCast( DirectCast( results( 0I) , ManagementBaseObject) .
Properties ( "ExecutablePath" ) .Value , String )
Else
Return String .Empty
End If
End Using
End Using
End Function
6569
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets)
en: 2 Octubre 2014, 04:12 am
Bueno, ya que nadie me da nunca las gracias por mis aportaciones de Snippets los cuales voy publicando casi día tras día o semana tras semana, y ya que no recibo ni un piropo ni una sonrisa por esto (xD), pues escribo este OffTopic para darme un poquito de reconocimiento a mi mismo, porque yo lo valgo xD.
Así es un día cualquiera en la vida de
Elektro actualizando un antiguo Snippet (los
breakpoints creo que no se restauran al darle ctrl+z), esto es para que veais que le pongo mucho empeño para compartir códigos con todos vosotros... y que todo es de cosecha propia, bueno, y porque en realidad siempre quise hacer algún video de este estilo a lo
speed-coding , aunque no he elegido el mejor código/snippet para hacer este tipo de video, pero tenia muchas ganas de hacerlo xD:
VIDEO Si, ha sido una chorrada de video y de comentario, ¿y que?, ¡a ver si os animais a compartir Snippets!... que siempre soy el único
Saludos!
6570
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets)
en: 2 Octubre 2014, 03:34 am
He tomado una antigua class del cajón de los recuerdos (o experimentos xD) que servía como medidor de tiempo para un cronómetro o una cuenta atrás y lo he mejorado y simplificado bastante.
Ejemplo de uso:
Public Class form1
''' <summary>
''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
''' </summary>
Private WithEvents Clock As New TimeMeasurer With { .UpdateInterval = 100 }
Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
Private Shadows Sub Load( ) Handles MyBase .Load
ctrl_ElapsedTime = Label1
ctrl_RemainingTime = Label2
Me .Clock .Start ( 60000 ) ' Measure 1 minute
' Or...
' Me.Clock.Stop() ' Stop temporally the time interval measurement.
' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
End Sub
Private Sub Clock_ElapsedTimeUpdated( ByVal sender As Object , ByVal e As TimeMeasurer.TimeMeasureEventArgs ) _
Handles Clock.ElapsedTimeUpdated
' Measure H:M:S:MS
ctrl_ElapsedTime.Text = String .Format ( "{0:00}:{1:00}:{2:00}:{3:000}" ,
e.Hour , e.Minute , e.Second , e.Millisecond )
End Sub
Private Sub Clock_RemainingTimeUpdated( ByVal sender As Object , ByVal e As TimeMeasurer.TimeMeasureEventArgs ) _
Handles Clock.RemainingTimeUpdated
' Measure H:M:S:MS
ctrl_RemainingTime.Text = String .Format ( "{0:00}:{1:00}:{2:00}:{3:000}" ,
e.Hour , e.Minute , e.Second , e.Millisecond )
'' Measure H:M:S
'ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
' e.Hour, e.Minute, e.Second + 1)
End Sub
Private Sub Clock_ElapsedTimeFinished( ByVal sender As Object , ByVal e As TimeMeasurer.TimeMeasureEventArgs ) _
Handles Clock.ElapsedTimeFinished
' Measure H:M:S:MS
ctrl_ElapsedTime.Text = String .Format ( "{0:00}:{1:00}:{2:00}:{3:000}" ,
e.Hour , e.Minute , e.Second , e.Millisecond )
End Sub
Private Sub Clock_RemainingTimeFinished( ByVal sender As Object , ByVal e As TimeMeasurer.TimeMeasureEventArgs ) _
Handles Clock.RemainingTimeFinished
' Measure H:M:S:MS
ctrl_RemainingTime.Text = String .Format ( "{0:00}:{1:00}:{2:00}:{3:000}" ,
e.Hour , e.Minute , e.Second , e.Millisecond )
End Sub
End Class
Como veis es muy sencillo de usar y de una manera más genérica (mucho más que el antiguo código que ecribí)
El source:
' ***********************************************************************
' Author : Elektro
' Last Modified On : 10-02-2014
' ***********************************************************************
' <copyright file="TimeMeasurer.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Usage Examples "
'Public Class TimeMeasurer_Test
'
' ''' <summary>
' ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
' ''' </summary>
' Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}
'
' Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
' Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
'
' Private Shadows Sub Load() Handles MyBase.Load
'
' ctrl_ElapsedTime = LabelElapsed
' ctrl_RemainingTime = LabelRemaining
'
' Me.Clock.Start(60000) ' Measure 1 minute
'
' ' Or...
' ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
' ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
' ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
'
' End Sub
'
' ''' <summary>
' ''' Handles the ElapsedTimeUpdated event of the Clock instance.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
' Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
' Handles Clock.ElapsedTimeUpdated
'
' ' Measure H:M:S:MS
' ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
' e.Hour, e.Minute, e.Second, e.Millisecond)
'
' ' Measure H:M:S
' ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
' e.Hour, e.Minute, e.Second)
'
' End Sub
'
' ''' <summary>
' ''' Handles the RemainingTimeUpdated event of the Clock instance.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
' Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
' Handles Clock.RemainingTimeUpdated
'
' ' Measure H:M:S:MS
' ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
' e.Hour, e.Minute, e.Second, e.Millisecond)
'
' ' Measure H:M:S
' ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
' e.Hour, e.Minute, e.Second + 1)
'
' End Sub
'
' ''' <summary>
' ''' Handles the ElapsedTimeFinished event of the Clock instance.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
' Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
' Handles Clock.ElapsedTimeFinished
'
' ' Measure H:M:S:MS
' ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
' e.Hour, e.Minute, e.Second, e.Millisecond)
'
' ' Measure H:M:S
' ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
' e.Hour, e.Minute, e.Second)
'
' End Sub
'
' ''' <summary>
' ''' Handles the RemainingTimeFinished event of the Clock instance.
' ''' </summary>
' ''' <param name="sender">The source of the event.</param>
' ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
' Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
' Handles Clock.RemainingTimeFinished
'
' ' Measure H:M:S:MS
' ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
' e.Hour, e.Minute, e.Second, e.Millisecond)
'
' ' Measure H:M:S
' ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
' e.Hour, e.Minute, e.Second)
'
' End Sub
'
'End Class
#End Region
#Region " Option Statements "
Option Strict On
Option Explicit On
Option Infer Off
#End Region
#Region " Imports "
Imports System.ComponentModel
#End Region
''' <summary>
''' Measure a time interval.
''' This can be used as a chronometer or countdown timer.
''' </summary>
Public NotInheritable Class TimeMeasurer
#Region " Objects "
''' <summary>
''' <see cref="Stopwatch"/> instance to retrieve the elapsed time.
''' </summary>
Private TimeElapsed As Stopwatch
''' <summary>
''' <see cref="TimeSpan"/> instance to retrieve the remaining time.
''' </summary>
Private TimeRemaining As TimeSpan
''' <summary>
''' <see cref="Timer"/> instance that updates the elapsed and remaining times and raises the events.
''' </summary>
Private WithEvents MeasureTimer As Timer
''' <summary>
''' Indicates wheter the <see cref="TimeMeasurer"/> instance has finished to measure intervals.
''' </summary>
Private IsFinished As Boolean
#End Region
#Region " Properties "
''' <summary>
''' Gets the current state of this <see cref="TimeMeasurer"/> instance.
''' </summary>
''' <value>The update interval.</value>
Public ReadOnly Property State As TimeMeasurerState
Get
If Me .IsFinished Then
Return TimeMeasurerState.Finished
ElseIf ( Me .TimeElapsed Is Nothing ) OrElse Not ( Me .TimeElapsed .IsRunning ) Then
Return TimeMeasurerState.Stopped
Else
Return TimeMeasurerState.Running
End If
End Get
End Property
''' <summary>
''' Gets or sets the update interval.
''' </summary>
''' <value>The update interval.</value>
Public Property UpdateInterval As Integer
Get
Return Me ._UpdateInterval
End Get
Set ( ByVal value As Integer )
Me ._UpdateInterval = value
If Me .MeasureTimer IsNot Nothing Then
Me .MeasureTimer .Interval = value
End If
End Set
End Property
''' <summary>
''' The update interval
''' </summary>
Private _UpdateInterval As Integer = 100I
#End Region
#Region " Enumerations "
''' <summary>
''' Specifies the current state of a <see cref="TimeMeasurer"/> instance.
''' </summary>
<Description( "Enum used as return value of 'State' property." ) >
Public Enum TimeMeasurerState As Integer
''' <summary>
''' The <see cref="TimeMeasurer"/> instance is running and measuring time intervals.
''' </summary>
Running = 0I
''' <summary>
''' The <see cref="TimeMeasurer"/> instance is temporally stopped, waiting to resume.
''' </summary>
Stopped = 1I
''' <summary>
''' The <see cref="TimeMeasurer"/> instance has finished to measure the time intervals.
''' </summary>
Finished = 2I
End Enum
#End Region
#Region " Events "
''' <summary>
''' Occurs when the elapsed time updates.
''' </summary>
Public Event ElapsedTimeUpdated( ByVal sender As Object , ByVal e As TimeMeasureEventArgs)
''' <summary>
''' Occurs when the remaining time updates.
''' </summary>
Public Event RemainingTimeUpdated( ByVal sender As Object , ByVal e As TimeMeasureEventArgs)
''' <summary>
''' Occurs when the elapsed time finishes.
''' </summary>
Public Event ElapsedTimeFinished( ByVal sender As Object , ByVal e As TimeMeasureEventArgs)
''' <summary>
''' Occurs when the elapsed time finishes.
''' </summary>
Public Event RemainingTimeFinished( ByVal sender As Object , ByVal e As TimeMeasureEventArgs)
''' <summary>
''' Contains the <see cref="TimeMeasureEventArgs"/> arguments.
''' </summary>
Public Class TimeMeasureEventArgs : Inherits EventArgs
''' <summary>
''' Gets or sets the hour.
''' </summary>
''' <value>The hour.</value>
Public Property Hour As Double
''' <summary>
''' Gets or sets the minute.
''' </summary>
''' <value>The minute.</value>
Public Property Minute As Double
''' <summary>
''' Gets or sets the Second.
''' </summary>
''' <value>The Second.</value>
Public Property Second As Double
''' <summary>
''' Gets or sets the Millisecond.
''' </summary>
''' <value>The Millisecond.</value>
Public Property Millisecond As Double
End Class
#End Region
#Region " Public Methods "
''' <summary>
''' Starts the time interval measurement from zero.
''' </summary>
''' <param name="Milliseconds">Indicates the time interval to measure, in milliseconds.</param>
Public Sub Start( ByVal Milliseconds As Double )
If Milliseconds > ( TimeSpan.MaxValue .TotalMilliseconds - 1001.0R) Then
Throw New ArgumentOutOfRangeException( "Milliseconds" ,
String .Format ( "The value can't be greater than {0}" ,
CStr ( TimeSpan.MaxValue .TotalMilliseconds - 1001.0R) ) )
End If
Me .TimeElapsed = New Stopwatch
Me .TimeRemaining = TimeSpan.FromMilliseconds ( Milliseconds)
Me .MeasureTimer = New Timer With
{
.Tag = Milliseconds,
.Interval = Me .UpdateInterval ,
.Enabled = True
}
Me .TimeElapsed .Start ( )
Me .MeasureTimer .Start ( )
End Sub
''' <summary>
''' Stops the time interval measurement.
''' </summary>
Public Sub [ Stop ] ( )
If ( Me .MeasureTimer Is Nothing ) OrElse Not ( Me .TimeElapsed .IsRunning ) Then
Throw New Exception( "TimeMeasurer is not running." )
Else
Me .MeasureTimer .Stop ( )
Me .TimeElapsed .Stop ( )
End If
End Sub
''' <summary>
''' Resumes the time interval measurement.
''' </summary>
Public Sub [ Resume ] ( )
If ( Me .MeasureTimer Is Nothing ) OrElse ( Me .TimeElapsed .IsRunning ) Then
Throw New Exception( "TimeMeasurer is not stopped." )
Else
Me .MeasureTimer .Start ( )
Me .TimeElapsed .Start ( )
End If
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Stops Time intervals and resets the elapsed and remaining time to zero.
''' </summary>
Private Sub Reset ( )
Me .MeasureTimer .Stop ( )
Me .TimeElapsed .Reset ( )
End Sub
#End Region
#Region " Event Handlers "
''' <summary>
''' Handles the Tick event of the MeasureTimer control.
''' </summary>
''' <param name="sender">The source of the event.</param>
''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
Private Sub MeasureTimer_Tick( ByVal sender As Object , ByVal e As EventArgs) _
Handles MeasureTimer.Tick
Dim TimeDifference As TimeSpan = ( Me .TimeRemaining - Me .TimeElapsed .Elapsed )
Dim ElapsedArgs As New TimeMeasureEventArgs
Dim RemainingArgs As New TimeMeasureEventArgs
If ( TimeDifference.TotalMilliseconds <= 0.0R) _
OrElse ( Me .TimeElapsed .ElapsedMilliseconds > DirectCast( Me .MeasureTimer .Tag , Double ) ) Then
Dim TotalTime As TimeSpan = TimeSpan.FromMilliseconds ( DirectCast( Me .MeasureTimer .Tag , Double ) )
With ElapsedArgs
.Hour = TotalTime.Hours
.Minute = TotalTime.Minutes
.Second = TotalTime.Seconds
.Millisecond = TotalTime.Milliseconds
End With
With RemainingArgs
.Hour = 0.0R
.Minute = 0.0R
.Second = 0.0R
.Millisecond = 0.0R
End With
Me .Reset ( )
Me .IsFinished = True
RaiseEvent ElapsedTimeFinished( Me .TimeElapsed , ElapsedArgs)
RaiseEvent RemainingTimeFinished( TimeDifference, RemainingArgs)
Else
With ElapsedArgs
.Hour = TimeElapsed.Elapsed .Hours
.Minute = TimeElapsed.Elapsed .Minutes
.Second = TimeElapsed.Elapsed .Seconds
.Millisecond = TimeElapsed.Elapsed .Milliseconds
End With
With RemainingArgs
.Hour = Math.Floor ( TimeDifference.TotalHours ) Mod TimeSpan.MaxValue .TotalMilliseconds
.Minute = Math.Floor ( TimeDifference.TotalMinutes ) Mod 60.0R
.Second = Math.Floor ( TimeDifference.TotalSeconds ) Mod 60.0R
.Millisecond = Math.Floor ( TimeDifference.TotalMilliseconds Mod 1000.0R)
End With
RaiseEvent ElapsedTimeUpdated( Me .TimeElapsed , ElapsedArgs)
RaiseEvent RemainingTimeUpdated( TimeDifference, RemainingArgs)
End If
End Sub
#End Region
End Class