6741
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!
6742
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
6743
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
6744
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!
6745
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
6746
Sistemas Operativos / Windows / Re: Windows 9 se llamará Windows 10. Novedades del sistema operativo de Microsoft
en: 2 Octubre 2014, 00:19 am
"Windows 9 se llamará Windows 10 ", ¿esa afirmación no es ningún Hoax ?, ¿hay alguna fuente verificable donde no especulen y expliquen porque este repentino y extraño cambio de nombre que no sigue la linea conceptual de Microsoft?, no tiene sentido para mi que salten del 8.1 al 10. Eso sí, en mi opinión, desde luego que se van a ahorrar muchos pero que muchos millones en mantenimiento, supervisión, y en el desarrollo de su sistema operativo uni-plataforma precisamente por eso, y además siendo positivos el servicio técnico de atención al cliente al igual que los desarrolladores de este nuevo Windows ¿10? estarán mucho más cualificados y su rendimiento general será más elevado al estar trabajando todos en un SO donde seguramente solo se diferenciará en algunas cosas breves como características especialmente para móviles, etc, o quizás ni en eso, o yo que se, pero me parece una apuesta efectiva a la vez que económica y rentable para ellos, creo que van a ahorrar muchisimo, es más, creo que lo hacen precisamente por que se han dado cuenta de ese detalle económico y han descubierto la manera de llevarlo a cabo, y ese sistema uni plataforma les acabará dando más poder del que ya tienen. Un saludo!
6749
Programación / Programación General / Re: [EHN-Dev 2014] - Concurso de desarrollo de aplicaciones (Hilo oficial)
en: 1 Octubre 2014, 17:45 pm
Proyecto.....: Hot Corners Autor........: Eleкtro Descripción..: Personaliza y realiza una acción específica cuando el mouse está sobre una esquina de la pantalla. Lenguaje.....: VB.Net Tecnología...: Windows Forms Framework....: 4.0 Arquitectura.: MSIL (Neutro), x86, y x64 Idioma.......: Inglés Dependencias.: Telerik UI for WinForms, Ooki Dialogs. Licencia.....: Ninguna, los de Telerik me prohiben algunas cosas, pero comparto el proyecto de forma libre respetando sus clausuras. Total Lineas.: 9.500 lineas de código, más o menos. Descarga.....: https://www.mediafire.com/?2h11t1dkulel417 Observaciones: Leer el readme en Español que hay dentro de la descarga para saber donde está el programa, y donde el source. Testeado en XP, 7, 8, y 8.1 (en XP no funciona la acción ToggleDesktop, la he deshabilitado para ese S.O.)El resto de detalles de esta presentación:
Descripción
Hot corners le ayudará en el día a día facilitándole tareas cotidianas, ya que viene con un conjunto de acciones integradas totalmente personalizables que se pueden iniciar cuando el ratón está en una esquina de la pantalla.
Características
Las esquinas activas también se conocen como una función predeterminada que viene incluida en Microsoft Windows 8, pero a diferencia de la característica de Microsoft,
Hot Corners realiza una acción específica y personalizada cuando el ratón está sobre una de las esquinas disponibles en la pantalla, Superior izquierda, Superior derecha, Inferior izquierda o Inferior derecha.
Seguimiento interno del ratón La aplicación mantiene internamente el seguimiento de la actividad del ratón para mejorar el rendimiento y ahorrar consumo de CPU al cambiar a un estado inactivo mientras no haya actividad por parte del ratón.
Hot Corners no es intrusivo con el SO, sólo hace su trabajo cuando el ratón está activo.
Personalizador de acciones Cada esquina se puede configurar para realizar una de las acciones incluidas en la aplicación,
como ejecutar cualquier archivo o proceso con parámetros específicos, explorar cualquier archivo o carpeta, visitar una página web, lanzar un comando del panel de control, y mucho más.
Cada corner puede ser activado o desactivado en cualquier momento a través del menú principal de la aplicación.
Cualquier proceso se puede añadir a una lista negra para abortar una activación de la esquina, esto es útil por ejemplo cuando se está jugando a juegos en pantalla completa.
La zona de las esquinas se puede personalizar para cumplir sus necesidades.
Personalizador de intervalos internos Los intervalos internos de la aplicación se pueden personalizar mediante el menú principal para ayudar a mejorar el rendimiento,
como el tiempo necesario para activar una esquina, o el intervalo de retardo para llevar a cabo una primera comprobación después de que se detecte actividad del ratón.
Selección de Monitor activo Hot Corners se pueden configurar para trabajar en un monitor específico, o incluso en una pantalla dual.
La aplicación se puede configurar para iniciar automáticamente cuando el usuario actual inicie sesión en Windows.
Le ayuda a descubrir los mejores valores para la configuración de las esquinas, y también para identificar posibles problemas debido a una configuración erronea al ver lo que sucede a cada momento en tiempo real.
Restablecer configuración La configuración personalizada de cada esquina se pueden resetear haciendo un solo click.
Imágenes
Demostración
VIDEO
Observaciones
Espero que a alguien le sirva de utilidad la aplicación, cualquier fallo en el programa me avisan para intentar corregirlo (a partir del 20 de Octubre del 2014, cuando acaba el concurso), gracias por haber leido hasta aquí
.
Saludos!
6750
Programación / .NET (C#, VB.NET, ASP) / [Source] Hot Corners
en: 1 Octubre 2014, 17:42 pm
Descripción
Hot corners le ayudará en el día a día facilitándole tareas cotidianas, ya que viene con un conjunto de acciones integradas totalmente personalizables que se pueden iniciar cuando el ratón está en una esquina de la pantalla.
Nota: Esta aplicación la he desarrollado expresamente para participar el concurso
EHN-DEV 2014 , y porque no me viene nada mal el programa xD.
Detalles Técnicos
Proyecto....: Hot Corners Autor.......: Elektro Descirpción.: Realiza una acción específica cuando el mouse está sobre una esquina de la pantalla. Versión.....: 1.0.0.0 Fecha.......: 30/Sep/2014 Lenguaje....: VB.Net Tecnología..: Windows Forms Framework...: 4.0 Arquitectura: MSIL (Neutro), x86, y x64 Idioma......: Inglés Dependencias: Telerik UI for WinForms, Ooki Dialogs. Características
Las esquinas activas también se conocen como una función predeterminada que viene incluida en Microsoft Windows 8, pero a diferencia de la característica de Microsoft,
Hot Corners realiza una acción específica y personalizada cuando el ratón está sobre una de las esquinas disponibles en la pantalla, Superior izquierda, Superior derecha, Inferior izquierda o Inferior derecha.
Seguimiento interno del ratón La aplicación mantiene internamente el seguimiento de la actividad del ratón para mejorar el rendimiento y ahorrar consumo de CPU al cambiar a un estado inactivo mientras no haya actividad por parte del ratón.
Hot Corners no es intrusivo con el SO, sólo hace su trabajo cuando el ratón está activo.
Personalizador de acciones Cada esquina se puede configurar para realizar una de las acciones incluidas en la aplicación,
como ejecutar cualquier archivo o proceso con parámetros específicos, explorar cualquier archivo o carpeta, visitar una página web, lanzar un comando del panel de control, y mucho más.
Cada corner puede ser activado o desactivado en cualquier momento a través del menú principal de la aplicación.
Cualquier proceso se puede añadir a una lista negra para abortar una activación de la esquina, esto es útil por ejemplo cuando se está jugando a juegos en pantalla completa.
La zona de las esquinas se puede personalizar para cumplir sus necesidades.
Personalizador de intervalos internos Los intervalos internos de la aplicación se pueden personalizar mediante el menú principal para ayudar a mejorar el rendimiento,
como el tiempo necesario para activar una esquina, o el intervalo de retardo para llevar a cabo una primera comprobación después de que se detecte actividad del ratón.
Selección de Monitor activo Hot Corners se pueden configurar para trabajar en un monitor específico, o incluso en una pantalla dual.
La aplicación se puede configurar para iniciar automáticamente cuando el usuario actual inicie sesión en Windows.
Le ayuda a descubrir los mejores valores para la configuración de las esquinas, y también para identificar posibles problemas debido a una configuración erronea al ver lo que sucede a cada momento en tiempo real.
Restablecer configuración La configuración personalizada de cada esquina se pueden resetear haciendo un solo click.
Imágenes
Demostración
VIDEO
Descarga
https://www.mediafire.com/?2h11t1dkulel417 Espero que a alguien le sirva de utilidad la aplicación, cualquier fallo en el programa me avisan para intentar corregirlo (a partir del 20 de Octubre del 2014, cuando acaba el concurso), gracias por haber leido hasta aquí
.
Saludos!