elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado:


  Mostrar Mensajes
Páginas: 1 ... 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 [657] 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 ... 1236
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:
Código:
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 :P



EDITO:
Un ejemplo Visual:




¿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:

Código
  1. Windows Registry Editor Version 5.00
  2.  
  3. [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]
  4. "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 :P.

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!
6565  Programación / Scripting / Re: .bat para compilar con Javac en: 2 Octubre 2014, 18:10 pm
Lo sé, pero he comentado que los ordenadores del centro están bastante capados y por ejemplo para cosas como estas no tengo los suficientes permisos.

¿Has probado a añadir el directorio al PATH de manera permanente desde la consola?:

Código
  1. "%SystemRoot%\System32\SetX.exe" PATH "%PATH%;%ProgramFiles%\Java\jdk1.7.0_25\bin" /M

De todas formas te recomiendo utilizar mi aplicación, no tiene ningún beneficio sobre los permisos de usuario, pero tiene bastantes opciones que te podrían resultar útiles:

http://foro.elhacker.net/net/source_paths_administra_las_entradas_de_las_variables_de_entorno_path_y-t398347.0.html;msg1883825#msg1883825



Ejemplo de uso:

Código
  1. PATHS.exe /Add -Local "%ProgramFiles%\Java\jdk1.7.0_25\bin"

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.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 10-02-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SetWindowState.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Dim HWND As IntPtr = Process.GetProcessesByName("devenv").First.MainWindowHandle
  13. '
  14. 'SetWindowState.SetWindowState(HWND, SetWindowState.WindowState.Hide)
  15. 'SetWindowState.SetWindowState("devenv", SetWindowState.WindowState.Restore, Recursivity:=False)
  16.  
  17. #End Region
  18.  
  19. #Region " Imports "
  20.  
  21. Imports System.Runtime.InteropServices
  22.  
  23. #End Region
  24.  
  25. ''' <summary>
  26. ''' Sets the state of a window.
  27. ''' </summary>
  28. Public NotInheritable Class SetWindowState
  29.  
  30. #Region " P/Invoke "
  31.  
  32.    ''' <summary>
  33.    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  34.    ''' This class does not suppress stack walks for unmanaged code permission.
  35.    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
  36.    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
  37.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
  38.    ''' </summary>
  39.    Protected NotInheritable Class NativeMethods
  40.  
  41. #Region " Methods "
  42.  
  43.        ''' <summary>
  44.        ''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
  45.        ''' This function does not search child windows.
  46.        ''' This function does not perform a case-sensitive search.
  47.        ''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
  48.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
  49.        ''' </summary>
  50.        ''' <param name="lpClassName">The class name.
  51.        ''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
  52.        ''' <param name="lpWindowName">The window name (the window's title).
  53.        ''' If this parameter is NULL, all window names match.</param>
  54.        ''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
  55.        ''' If the function fails, the return value is NULL.</returns>
  56.        <DllImport("user32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False)>
  57.        Friend Shared Function FindWindow(
  58.           ByVal lpClassName As String,
  59.           ByVal lpWindowName As String
  60.        ) As IntPtr
  61.        End Function
  62.  
  63.        ''' <summary>
  64.        ''' Retrieves a handle to a window whose class name and window name match the specified strings.
  65.        ''' The function searches child windows, beginning with the one following the specified child window.
  66.        ''' This function does not perform a case-sensitive search.
  67.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633500%28v=vs.85%29.aspx
  68.        ''' </summary>
  69.        ''' <param name="hwndParent">
  70.        ''' A handle to the parent window whose child windows are to be searched.
  71.        ''' If hwndParent is NULL, the function uses the desktop window as the parent window.
  72.        ''' The function searches among windows that are child windows of the desktop.
  73.        ''' </param>
  74.        ''' <param name="hwndChildAfter">
  75.        ''' A handle to a child window.
  76.        ''' The search begins with the next child window in the Z order.
  77.        ''' The child window must be a direct child window of hwndParent, not just a descendant window.
  78.        ''' If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.
  79.        ''' </param>
  80.        ''' <param name="strClassName">
  81.        ''' The window class name.
  82.        ''' </param>
  83.        ''' <param name="strWindowName">
  84.        ''' The window name (the window's title).
  85.        ''' If this parameter is NULL, all window names match.
  86.        ''' </param>
  87.        ''' <returns>
  88.        ''' If the function succeeds, the return value is a handle to the window that has the specified class and window names.
  89.        ''' If the function fails, the return value is NULL.
  90.        ''' </returns>
  91.        <DllImport("User32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False)>
  92.        Friend Shared Function FindWindowEx(
  93.           ByVal hwndParent As IntPtr,
  94.           ByVal hwndChildAfter As IntPtr,
  95.           ByVal strClassName As String,
  96.           ByVal strWindowName As String
  97.        ) As IntPtr
  98.        End Function
  99.  
  100.        ''' <summary>
  101.        ''' Retrieves the identifier of the thread that created the specified window
  102.        ''' and, optionally, the identifier of the process that created the window.
  103.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx
  104.        ''' </summary>
  105.        ''' <param name="hWnd">A handle to the window.</param>
  106.        ''' <param name="ProcessId">
  107.        ''' A pointer to a variable that receives the process identifier.
  108.        ''' If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable;
  109.        ''' otherwise, it does not.
  110.        ''' </param>
  111.        ''' <returns>The identifier of the thread that created the window.</returns>
  112.        <DllImport("user32.dll")>
  113.        Friend Shared Function GetWindowThreadProcessId(
  114.            ByVal hWnd As IntPtr,
  115.            ByRef ProcessId As Integer
  116.        ) As Integer
  117.        End Function
  118.  
  119.        ''' <summary>
  120.        ''' Sets the specified window's show state.
  121.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
  122.        ''' </summary>
  123.        ''' <param name="hwnd">A handle to the window.</param>
  124.        ''' <param name="nCmdShow">Controls how the window is to be shown.</param>
  125.        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  126.        <DllImport("User32", SetLastError:=False)>
  127.        Friend Shared Function ShowWindow(
  128.           ByVal hwnd As IntPtr,
  129.           ByVal nCmdShow As WindowState
  130.        ) As Boolean
  131.        End Function
  132.  
  133. #End Region
  134.  
  135.    End Class
  136.  
  137. #End Region
  138.  
  139. #Region " Enumerations "
  140.  
  141.    ''' <summary>
  142.    ''' Controls how the window is to be shown.
  143.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
  144.    ''' </summary>
  145.    Friend Enum WindowState As Integer
  146.  
  147.        ''' <summary>
  148.        ''' Hides the window and activates another window.
  149.        ''' </summary>
  150.        Hide = 0I
  151.  
  152.        ''' <summary>
  153.        ''' Activates and displays a window.
  154.        ''' If the window is minimized or maximized, the system restores it to its original size and position.
  155.        ''' An application should specify this flag when displaying the window for the first time.
  156.        ''' </summary>
  157.        Normal = 1I
  158.  
  159.        ''' <summary>
  160.        ''' Activates the window and displays it as a minimized window.
  161.        ''' </summary>
  162.        ShowMinimized = 2I
  163.  
  164.        ''' <summary>
  165.        ''' Maximizes the specified window.
  166.        ''' </summary>
  167.        Maximize = 3I
  168.  
  169.        ''' <summary>
  170.        ''' Activates the window and displays it as a maximized window.
  171.        ''' </summary>      
  172.        ShowMaximized = Maximize
  173.  
  174.        ''' <summary>
  175.        ''' Displays a window in its most recent size and position.
  176.        ''' This value is similar to <see cref="WindowState.Normal"/>, except the window is not actived.
  177.        ''' </summary>
  178.        ShowNoActivate = 4I
  179.  
  180.        ''' <summary>
  181.        ''' Activates the window and displays it in its current size and position.
  182.        ''' </summary>
  183.        Show = 5I
  184.  
  185.        ''' <summary>
  186.        ''' Minimizes the specified window and activates the next top-level window in the Z order.
  187.        ''' </summary>
  188.        Minimize = 6I
  189.  
  190.        ''' <summary>
  191.        ''' Displays the window as a minimized window.
  192.        ''' This value is similar to <see cref="WindowState.ShowMinimized"/>, except the window is not activated.
  193.        ''' </summary>
  194.        ShowMinNoActive = 7I
  195.  
  196.        ''' <summary>
  197.        ''' Displays the window in its current size and position.
  198.        ''' This value is similar to <see cref="WindowState.Show"/>, except the window is not activated.
  199.        ''' </summary>
  200.        ShowNA = 8I
  201.  
  202.        ''' <summary>
  203.        ''' Activates and displays the window.
  204.        ''' If the window is minimized or maximized, the system restores it to its original size and position.
  205.        ''' An application should specify this flag when restoring a minimized window.
  206.        ''' </summary>
  207.        Restore = 9I
  208.  
  209.        ''' <summary>
  210.        ''' Sets the show state based on the SW_* value specified in the STARTUPINFO structure
  211.        ''' passed to the CreateProcess function by the program that started the application.
  212.        ''' </summary>
  213.        ShowDefault = 10I
  214.  
  215.        ''' <summary>
  216.        ''' <b>Windows 2000/XP:</b>
  217.        ''' Minimizes a window, even if the thread that owns the window is not responding.
  218.        ''' This flag should only be used when minimizing windows from a different thread.
  219.        ''' </summary>
  220.        ForceMinimize = 11I
  221.  
  222.    End Enum
  223.  
  224. #End Region
  225.  
  226. #Region " Public Methods "
  227.  
  228.    ''' <summary>
  229.    ''' Set the state of a window by an HWND.
  230.    ''' </summary>
  231.    ''' <param name="WindowHandle">A handle to the window.</param>
  232.    ''' <param name="WindowState">The state of the window.</param>
  233.    ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  234.    Friend Shared Function SetWindowState(ByVal WindowHandle As IntPtr,
  235.                                          ByVal WindowState As WindowState) As Boolean
  236.  
  237.        Return NativeMethods.ShowWindow(WindowHandle, WindowState)
  238.  
  239.    End Function
  240.  
  241.    ''' <summary>
  242.    ''' Set the state of a window by a process name.
  243.    ''' </summary>
  244.    ''' <param name="ProcessName">The name of the process.</param>
  245.    ''' <param name="WindowState">The state of the window.</param>
  246.    ''' <param name="Recursivity">If set to <c>false</c>, only the first process instance will be processed.</param>
  247.    Friend Shared Sub SetWindowState(ByVal ProcessName As String,
  248.                                     ByVal WindowState As WindowState,
  249.                                     Optional ByVal Recursivity As Boolean = False)
  250.  
  251.        If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
  252.            ProcessName = ProcessName.Remove(ProcessName.Length - ".exe".Length)
  253.        End If
  254.  
  255.        Dim pHandle As IntPtr = IntPtr.Zero
  256.        Dim pID As Integer = 0I
  257.  
  258.        Dim Processes As Process() = Process.GetProcessesByName(ProcessName)
  259.  
  260.        ' If any process matching the name is found then...
  261.        If Processes.Count = 0 Then
  262.            Exit Sub
  263.        End If
  264.  
  265.        For Each p As Process In Processes
  266.  
  267.            ' If Window is visible then...
  268.            If p.MainWindowHandle <> IntPtr.Zero Then
  269.                SetWindowState(p.MainWindowHandle, WindowState)
  270.  
  271.            Else ' Window is hidden
  272.  
  273.                ' Check all open windows (not only the process we are looking),
  274.                ' begining from the child of the desktop, phandle = IntPtr.Zero initialy.
  275.                While pID <> p.Id ' Check all windows.
  276.  
  277.                    ' Get child handle of window who's handle is "pHandle".
  278.                    pHandle = NativeMethods.FindWindowEx(IntPtr.Zero, pHandle, Nothing, Nothing)
  279.  
  280.                    ' Get ProcessId from "pHandle".
  281.                    NativeMethods.GetWindowThreadProcessId(pHandle, pID)
  282.  
  283.                    ' If the ProcessId matches the "pID" then...
  284.                    If pID = p.Id Then
  285.  
  286.                        NativeMethods.ShowWindow(pHandle, WindowState)
  287.  
  288.                        If Not Recursivity Then
  289.                            Exit For
  290.                        End If
  291.  
  292.                    End If
  293.  
  294.                End While
  295.  
  296.            End If
  297.  
  298.        Next p
  299.  
  300.    End Sub
  301.  
  302. #End Region
  303.  
  304. 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...

Código
  1. Public Class MyType
  2.  
  3. ''' <summary>
  4. ''' Gets or sets the value.
  5. ''' </summary>
  6. ''' <value>The value.</value>
  7. Public Property MyProperty As Integer
  8.    Get
  9.        Return Me._MyValue
  10.    End Get
  11.    Set(ByVal value As Integer)
  12.  
  13.        If value < Me._MyValueMin Then
  14.            If Me._MyValueThrowRangeException Then
  15.                Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
  16.            End If
  17.            Me._MyValue = Me._MyValueMin
  18.  
  19.        ElseIf value > Me._MyValueMax Then
  20.            If Me._MyValueThrowRangeException Then
  21.                Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
  22.            End If
  23.            Me._MyValue = Me._MyValueMax
  24.  
  25.        Else
  26.            Me._MyValue = value
  27.  
  28.        End If
  29.  
  30.    End Set
  31. End Property
  32. Private _MyValue As Integer = 0I
  33. Private _MyValueMin As Integer = 0I
  34. Private _MyValueMax As Integer = 10I
  35. Private _MyValueThrowRangeException As Boolean = True
  36.    Private _MyValueExceptionMessage As String = String.Format("The valid range is beetwen {0} and {1}",
  37.                                                           Me._MyValueMin, Me._MyValueMax)
  38.  
  39. End Class




Una utilidad para mostrar, ocultar, o intercambiar el estado del escritorio.

Nota: El método ToggleDesktop no funciona en WinXP.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 09-23-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DesktopVisibility.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' DesktopVisibility.ShowDesktop()
  13. ' DesktopVisibility.HideDesktop()
  14. ' DesktopVisibility.ToggleDesktop()
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports System.Runtime.InteropServices
  21.  
  22. #End Region
  23.  
  24. #Region " DesktopVisibility "
  25.  
  26. ''' <summary>
  27. ''' Shows, hides, or toggles the desktop.
  28. ''' </summary>
  29. Public NotInheritable Class DesktopVisibility
  30.  
  31. #Region " Objects "
  32.  
  33.    ''' <summary>
  34.    ''' "Shell" CLASSID.
  35.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776890%28v=vs.85%29.aspx
  36.    ''' </summary>
  37.    Private Shared ReadOnly CLSIDShell As New Guid("13709620-C279-11CE-A49E-444553540000")
  38.  
  39.    ''' <summary>
  40.    ''' Gets the objects in the Shell.
  41.    ''' Methods are provided to control the Shell and to execute commands within the Shell.
  42.    ''' There are also methods to obtain other Shell-related objects.
  43.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb774094%28v=vs.85%29.aspx
  44.    ''' </summary>
  45.    Private Shared ReadOnly Property Shell As Object
  46.        Get
  47.            If _Shell Is Nothing Then
  48.                _Shell = Activator.CreateInstance(Type.GetTypeFromCLSID(CLSIDShell))
  49.                Return _Shell
  50.            Else
  51.                Return _Shell
  52.            End If
  53.        End Get
  54.    End Property
  55.    Private Shared _Shell As Object = Nothing
  56.  
  57. #End Region
  58.  
  59. #Region " P/Invoke "
  60.  
  61. #Region " Methods "
  62.  
  63.    ''' <summary>
  64.    ''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
  65.    ''' This function does not search child windows.
  66.    ''' This function does not perform a case-sensitive search.
  67.    ''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
  68.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
  69.    ''' </summary>
  70.    ''' <param name="lpClassName">The class name.
  71.    ''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
  72.    ''' <param name="lpWindowName">The window name (the window's title).
  73.    ''' If this parameter is NULL, all window names match.</param>
  74.    ''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
  75.    ''' If the function fails, the return value is NULL.</returns>
  76.    <DllImport("user32.dll", SetLastError:=False)>
  77.    Private Shared Function FindWindow(
  78.            ByVal lpClassName As String,
  79.            ByVal lpWindowName As String
  80.    ) As IntPtr
  81.    End Function
  82.  
  83.    ''' <summary>
  84.    ''' Sends the specified message to a window or windows.
  85.    ''' The SendMessage function calls the window procedure for the specified window
  86.    ''' and does not return until the window procedure has processed the message.
  87.    ''' </summary>
  88.    ''' <param name="hWnd">A handle to the window whose window procedure will receive the message.</param>
  89.    ''' <param name="Msg">The message to be sent.</param>
  90.    ''' <param name="wParam">Additional message-specific information.</param>
  91.    ''' <param name="lParam">Additional message-specific information.</param>
  92.    ''' <returns>IntPtr.</returns>
  93.    <DllImport("user32.dll", SetLastError:=False)>
  94.    Private Shared Function SendMessage(
  95.            ByVal hWnd As IntPtr,
  96.            ByVal Msg As WindowsMessages,
  97.            ByVal wParam As IntPtr,
  98.            ByVal lParam As IntPtr
  99.    ) As IntPtr
  100.    End Function
  101.  
  102. #End Region
  103.  
  104. #Region " Enumerations "
  105.  
  106.    ''' <summary>
  107.    ''' Specifies a System-Defined Message.
  108.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927%28v=vs.85%29.aspx#system_defined
  109.    ''' </summary>
  110.    Public Enum WindowsMessages
  111.  
  112.        ''' <summary>
  113.        ''' Message sent when the user selects a command item from a menu,
  114.        ''' when a control sends a notification message to its parent window,
  115.        ''' or when an accelerator keystroke is translated.
  116.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms647591%28v=vs.85%29.aspx
  117.        ''' </summary>
  118.        WM_COMMAND = &H111UI
  119.  
  120.    End Enum
  121.  
  122. #End Region
  123.  
  124. #Region " Constants "
  125.  
  126.    ''' <summary>
  127.    ''' Minimize all windows.
  128.    ''' </summary>
  129.    Const MIN_ALL As Integer = 419
  130.  
  131.    ''' <summary>
  132.    ''' Undo the minimization of all minimized windows.
  133.    ''' </summary>
  134.    Const MIN_ALL_UNDO As Integer = 416
  135.  
  136. #End Region
  137.  
  138. #End Region
  139.  
  140. #Region " Public Methods "
  141.  
  142.    ''' <summary>
  143.    ''' Shows the desktop.
  144.    ''' </summary>
  145.    Public Shared Sub ShowDesktop()
  146.  
  147.        SendMessage(FindWindow("Shell_TrayWnd", Nothing),
  148.                    WindowsMessages.WM_COMMAND,
  149.                    New IntPtr(MIN_ALL), IntPtr.Zero)
  150.  
  151.    End Sub
  152.  
  153.    ''' <summary>
  154.    ''' Hides the desktop.
  155.    ''' </summary>
  156.    Public Shared Sub HideDesktop()
  157.  
  158.        SendMessage(FindWindow("Shell_TrayWnd", Nothing),
  159.                    WindowsMessages.WM_COMMAND,
  160.                    New IntPtr(MIN_ALL_UNDO), IntPtr.Zero)
  161.  
  162.    End Sub
  163.  
  164.    ''' <summary>
  165.    ''' Shows or hides the desktop.
  166.    ''' </summary>
  167.    Public Shared Sub ToggleDesktop()
  168.  
  169.        Shell.ToggleDesktop() ' Doesns't works in Windows XP
  170.  
  171.    End Sub
  172.  
  173. #End Region
  174.  
  175. End Class
  176.  
  177. #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.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 10-01-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SetWindowPosition.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Example Usage "
  11.  
  12. ' SetWindowPosition.SetWindowPos("proceso.exe", SetWindowPosition.Corner.BottomRight)
  13. ' SetWindowPosition.SetWindowPos("proceso.exe", X:=100, Y:=100, Bounds:=SystemInformation.VirtualScreen)
  14.  
  15. #End Region
  16.  
  17. #Region " Imports "
  18.  
  19. Imports System.ComponentModel
  20. Imports System.Runtime.InteropServices
  21.  
  22. #End Region
  23.  
  24. ''' <summary>
  25. ''' Set the position of a window.
  26. ''' </summary>
  27. Public Class SetWindowPosition
  28.  
  29. #Region " P/Invoke "
  30.  
  31.    ''' <summary>
  32.    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  33.    ''' This class does not suppress stack walks for unmanaged code permission.
  34.    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
  35.    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
  36.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
  37.    ''' </summary>
  38.    Protected NotInheritable Class NativeMethods
  39.  
  40. #Region " Methods "
  41.  
  42.        ''' <summary>
  43.        ''' Changes the size, position, and Z order of a child, pop-up, or top-level window.
  44.        ''' These windows are ordered according to their appearance on the screen.
  45.        ''' The topmost window receives the highest rank and is the first window in the Z order.
  46.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  47.        ''' </summary>
  48.        ''' <param name="hWnd">
  49.        ''' A handle to the window.
  50.        ''' </param>
  51.        ''' <param name="hWndInsertAfter">
  52.        ''' A special handle to the window to precede the positioned window in the Z order.
  53.        ''' This parameter must be a window handle or one of the <see cref="SpecialWindowHandles"/> values.
  54.        ''' </param>
  55.        ''' <param name="X">
  56.        ''' The new position of the left side of the window, in client coordinates.
  57.        ''' </param>
  58.        ''' <param name="Y">
  59.        ''' The new position of the top of the window, in client coordinates.
  60.        ''' </param>
  61.        ''' <param name="cx">
  62.        ''' The new width of the window, in pixels.
  63.        ''' </param>
  64.        ''' <param name="cy">
  65.        ''' The new height of the window, in pixels.
  66.        ''' </param>
  67.        ''' <param name="uFlags">
  68.        ''' The window sizing and positioning flags.
  69.        ''' </param>
  70.        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  71.        <DllImport("user32.dll", SetLastError:=True)>
  72.        Friend Shared Function SetWindowPos(
  73.               ByVal hWnd As IntPtr,
  74.               ByVal hWndInsertAfter As SpecialWindowHandles,
  75.               ByVal X As Integer,
  76.               ByVal Y As Integer,
  77.               ByVal cx As Integer,
  78.               ByVal cy As Integer,
  79.               ByVal uFlags As SetWindowPosFlags
  80.        ) As Boolean
  81.        End Function
  82.  
  83.        ''' <summary>
  84.        ''' Retrieves the dimensions of the bounding rectangle of the specified window.
  85.        ''' The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
  86.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633519%28v=vs.85%29.aspx
  87.        ''' </summary>
  88.        ''' <param name="hWnd">A handle to the window.</param>
  89.        ''' <param name="rc">
  90.        ''' A pointer to a RECT structure that receives the screen coordinates of
  91.        ''' the upper-left and lower-right corners of the window.
  92.        ''' </param>
  93.        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  94.        <DllImport("user32.dll", SetLastError:=True)>
  95.        Friend Shared Function GetWindowRect(
  96.               ByVal hWnd As IntPtr,
  97.               ByRef rc As Rectangle
  98.        ) As Boolean
  99.        End Function
  100.  
  101. #End Region
  102.  
  103. #Region " Enumerations "
  104.  
  105.        ''' <summary>
  106.        ''' Specifies the window sizing and positioning flags.
  107.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  108.        ''' </summary>
  109.        <Description("Enum used as 'uFlags' parameter of 'NativeMethods.SetWindowPos' function")>
  110.        <Flags>
  111.        Friend Enum SetWindowPosFlags As UInteger
  112.  
  113.            ''' <summary>
  114.            ''' If the calling thread and the thread that owns the window are attached to different input queues,
  115.            ''' the system posts the request to the thread that owns the window.
  116.            ''' This prevents the calling thread from blocking its execution while other threads process the request.
  117.            ''' </summary>
  118.            ''' <remarks>SWP_ASYNCWINDOWPOS</remarks>
  119.            SynchronousWindowPosition = &H4000UI
  120.  
  121.            ''' <summary>
  122.            ''' Prevents generation of the WM_SYNCPAINT message.
  123.            ''' </summary>
  124.            ''' <remarks>SWP_DEFERERASE</remarks>
  125.            DeferErase = &H2000UI
  126.  
  127.            ''' <summary>
  128.            ''' Draws a frame (defined in the window's class description) around the window.
  129.            ''' </summary>
  130.            ''' <remarks>SWP_DRAWFRAME</remarks>
  131.            DrawFrame = &H20UI
  132.  
  133.            ''' <summary>
  134.            ''' Applies new frame styles set using the SetWindowLong function.
  135.            ''' Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed.
  136.            ''' If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
  137.            ''' </summary>
  138.            ''' <remarks>SWP_FRAMECHANGED</remarks>
  139.            FrameChanged = &H20UI
  140.  
  141.            ''' <summary>
  142.            ''' Hides the window.
  143.            ''' </summary>
  144.            ''' <remarks>SWP_HIDEWINDOW</remarks>
  145.            HideWindow = &H80UI
  146.  
  147.            ''' <summary>
  148.            ''' Does not activate the window.
  149.            ''' If this flag is not set, the window is activated and moved to the top of
  150.            ''' either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
  151.            ''' </summary>
  152.            ''' <remarks>SWP_NOACTIVATE</remarks>
  153.            DoNotActivate = &H10UI
  154.  
  155.            ''' <summary>
  156.            ''' Discards the entire contents of the client area. If this flag is not specified,
  157.            ''' the valid contents of the client area are saved and copied back into the
  158.            ''' client area after the window is sized or repositioned.
  159.            ''' </summary>
  160.            ''' <remarks>SWP_NOCOPYBITS</remarks>
  161.            DoNotCopyBits = &H100UI
  162.  
  163.            ''' <summary>
  164.            ''' Retains the current position (ignores X and Y parameters).
  165.            ''' </summary>
  166.            ''' <remarks>SWP_NOMOVE</remarks>
  167.            IgnoreMove = &H2UI
  168.  
  169.            ''' <summary>
  170.            ''' Does not change the owner window's position in the Z order.
  171.            ''' </summary>
  172.            ''' <remarks>SWP_NOOWNERZORDER</remarks>
  173.            DoNotChangeOwnerZOrder = &H200UI
  174.  
  175.            ''' <summary>
  176.            ''' Does not redraw changes.
  177.            ''' If this flag is set, no repainting of any kind occurs.
  178.            ''' This applies to  the client area, the nonclient area (including the title bar and scroll bars),
  179.            ''' and any part of the parent window uncovered as a result of the window being moved.
  180.            ''' When this flag is set, the application must explicitly invalidate or
  181.            ''' redraw any parts of the window and parent window that need redrawing.
  182.            ''' </summary>
  183.            ''' <remarks>SWP_NOREDRAW</remarks>
  184.            DoNotRedraw = &H8UI
  185.  
  186.            ''' <summary>
  187.            ''' Same as the SWP_NOOWNERZORDER flag.
  188.            ''' </summary>
  189.            ''' <remarks>SWP_NOREPOSITION</remarks>
  190.            DoNotReposition = &H200UI
  191.  
  192.            ''' <summary>
  193.            ''' Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
  194.            ''' </summary>
  195.            ''' <remarks>SWP_NOSENDCHANGING</remarks>
  196.            DoNotSendChangingEvent = &H400UI
  197.  
  198.            ''' <summary>
  199.            ''' Retains the current size (ignores the cx and cy parameters).
  200.            ''' </summary>
  201.            ''' <remarks>SWP_NOSIZE</remarks>
  202.            IgnoreResize = &H1UI
  203.  
  204.            ''' <summary>
  205.            ''' Retains the current Z order (ignores the hWndInsertAfter parameter).
  206.            ''' </summary>
  207.            ''' <remarks>SWP_NOZORDER</remarks>
  208.            IgnoreZOrder = &H4UI
  209.  
  210.            ''' <summary>
  211.            ''' Displays the window.
  212.            ''' </summary>
  213.            ''' <remarks>SWP_SHOWWINDOW</remarks>
  214.            ShowWindow = &H40UI
  215.  
  216.        End Enum
  217.  
  218.        ''' <summary>
  219.        ''' Specifies a special handle to the window to precede the positioned window in the Z order.
  220.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  221.        ''' </summary>
  222.        <Description("Enum used as 'hWndInsertAfter' parameter of 'NativeMethods.SetWindowPos' function")>
  223.        Friend Enum SpecialWindowHandles As Integer
  224.  
  225.            ''' <summary>
  226.            ''' Places the window at the top of the Z order.
  227.            ''' </summary>
  228.            Top = 0I
  229.  
  230.            ''' <summary>
  231.            ''' Places the window at the bottom of the Z order.
  232.            ''' If the hWnd parameter identifies a topmost window,
  233.            ''' the window loses its topmost status and is placed at the bottom of all other windows.
  234.            ''' </summary>
  235.            Bottom = 1I
  236.  
  237.            ''' <summary>
  238.            ''' Places the window above all non-topmost windows.
  239.            ''' The window maintains its topmost position even when it is deactivated.
  240.            ''' </summary>
  241.            TopMost = -1I
  242.  
  243.            ''' <summary>
  244.            ''' Places the window above all non-topmost windows (that is, behind all topmost windows).
  245.            ''' This flag has no effect if the window is already a non-topmost window.
  246.            ''' </summary>
  247.            NoTopMost = -2I
  248.  
  249.        End Enum
  250.  
  251. #End Region
  252.  
  253.    End Class
  254.  
  255. #End Region
  256.  
  257. #Region " Enumerations "
  258.  
  259.    ''' <summary>
  260.    ''' Specifies a screen corner.
  261.    ''' </summary>
  262.    <Description("Enum used as 'Corner' parameter of 'SetWindowPos' function")>
  263.    Friend Enum Corner As Integer
  264.  
  265.        ''' <summary>
  266.        ''' Top-Left screen corner.
  267.        ''' </summary>
  268.        TopLeft = 0I
  269.  
  270.        ''' <summary>
  271.        ''' Top-Right screen corner.
  272.        ''' </summary>
  273.        TopRight = 1I
  274.  
  275.        ''' <summary>
  276.        ''' Bottom-Left screen corner.
  277.        ''' </summary>
  278.        BottomLeft = 2I
  279.        ''' <summary>
  280.        ''' Bottom-Right screen corner.
  281.        ''' </summary>0
  282.        BottomRight = 3I
  283.  
  284.    End Enum
  285.  
  286. #End Region
  287.  
  288. #Region " Public Methods "
  289.  
  290.    ''' <summary>
  291.    ''' Set the position of a window.
  292.    ''' </summary>
  293.    ''' <param name="ProcessName">The process name.</param>
  294.    ''' <param name="Corner">The new window position, a screen corner.</param>
  295.    ''' <param name="Bounds">
  296.    ''' The screen <see cref="Rectangle"/> where the window is shown.
  297.    ''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
  298.    ''' </param>
  299.    Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
  300.                                   ByVal Corner As Corner,
  301.                                   Optional ByVal Bounds As Rectangle = Nothing)
  302.  
  303.        Dim Rect As Rectangle  ' The specified screen bounds
  304.        Dim HWND As IntPtr     ' The process main window handle.
  305.        Dim Width As Integer   ' The process window width.
  306.        Dim Height As Integer  ' The process window height.
  307.        Dim x As Integer
  308.        Dim y As Integer
  309.  
  310.        If Bounds.IsEmpty Then
  311.            Bounds = Screen.PrimaryScreen.WorkingArea
  312.        End If
  313.  
  314.        ' Iterate the process instances.
  315.        For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))
  316.  
  317.            Try
  318.                ' Get the main window handle.
  319.                HWND = p.MainWindowHandle
  320.  
  321.                ' Copy the process window position and size into the Rectangle.
  322.                ' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
  323.                NativeMethods.GetWindowRect(HWND, Rect)
  324.                Width = (Rect.Width - Rect.Left)    ' Set the window width
  325.                Height = (Rect.Height - Rect.Top) ' Set the window height
  326.  
  327.                Select Case Corner
  328.  
  329.                    Case SetWindowPosition.Corner.TopLeft
  330.                        x = Bounds.Left
  331.                        y = Bounds.Top
  332.  
  333.                    Case SetWindowPosition.Corner.TopRight
  334.                        x = Bounds.Right - Width
  335.                        y = Bounds.Top
  336.  
  337.                    Case SetWindowPosition.Corner.BottomLeft
  338.                        x = Bounds.Left
  339.                        y = Bounds.Bottom - Height
  340.  
  341.                    Case SetWindowPosition.Corner.BottomRight
  342.                        x = Bounds.Right - Width
  343.                        y = Bounds.Bottom - Height
  344.  
  345.                End Select
  346.  
  347.                ' Move the Main Window.
  348.                NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
  349.                                           x, y, 0, 0,
  350.                                           NativeMethods.SetWindowPosFlags.IgnoreResize)
  351.  
  352.            Catch ex As Exception
  353.                Throw
  354.  
  355.            End Try
  356.  
  357.        Next
  358.  
  359.    End Sub
  360.  
  361.    ''' <summary>
  362.    ''' Set the position of a window.
  363.    ''' </summary>
  364.    ''' <param name="ProcessName">The process name.</param>
  365.    ''' <param name="X">The new X coordinate.</param>
  366.    ''' <param name="Y">The new Y coordinate.</param>
  367.    ''' <param name="Bounds">
  368.    ''' The screen <see cref="Rectangle"/> where the window is shown.
  369.    ''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
  370.    ''' </param>
  371.    Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
  372.                             ByVal X As Integer,
  373.                             ByVal Y As Integer,
  374.                             Optional ByVal Bounds As Rectangle = Nothing)
  375.  
  376.        Dim Rect As Rectangle  ' The specified screen bounds
  377.        Dim HWND As IntPtr     ' The process main window handle.
  378.        Dim Width As Integer   ' The process window width.
  379.        Dim Height As Integer  ' The process window height.
  380.  
  381.        If Bounds.IsEmpty Then
  382.            Bounds = Screen.PrimaryScreen.WorkingArea
  383.        End If
  384.  
  385.        ' Iterate the process instances.
  386.        For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))
  387.  
  388.            Try
  389.                ' Get the main window handle.
  390.                HWND = p.MainWindowHandle
  391.  
  392.                ' Copy the process window position and size into the Rectangle.
  393.                ' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
  394.                NativeMethods.GetWindowRect(HWND, Rect)
  395.                Width = (Rect.Width - Rect.Left)  ' Set the window width
  396.                Height = (Rect.Height - Rect.Top) ' Set the window height
  397.  
  398.                ' Move the Main Window.
  399.                NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
  400.                                           x, y, 0, 0,
  401.                                           NativeMethods.SetWindowPosFlags.IgnoreResize)
  402.  
  403.            Catch ex As Exception
  404.                Throw
  405.  
  406.            End Try
  407.  
  408.        Next
  409.  
  410.    End Sub
  411.  
  412. #End Region
  413.  
  414. #Region " Private Methods "
  415.  
  416.    ''' <summary>
  417.    ''' Fixes the name of a process.
  418.    ''' </summary>
  419.    ''' <param name="name">The process name.</param>
  420.    ''' <returns>System.String.</returns>
  421.    Private Shared Function FixProcessName(ByVal name As String) As String
  422.  
  423.        If name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
  424.            Return name.Remove(name.Length - ".exe".Length)
  425.        Else
  426.            Return name
  427.        End If
  428.  
  429.    End Function
  430.  
  431. #End Region
  432.  
  433. End Class
  434.  





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.

Código
  1.        ' Add or remove application from Windows Startup
  2.        ' ( By Elektro )
  3.        '
  4.        ' Usage Examples :
  5.        ' AddApplicationToWindowsStartup(User.CurrentUser, Application.ProductName, Application.ExecutablePath)
  6.        ' RemoveApplicationFromWindowsStartup(User.CurrentUser, pplication.ProductName)
  7.  
  8.        ''' <summary>
  9.        ''' Specifies a registry user session.
  10.        ''' </summary>
  11.        Public Enum User As Integer
  12.  
  13.            ''' <summary>
  14.            ''' The current user session.
  15.            ''' </summary>
  16.            CurrentUser = 1I
  17.  
  18.            ''' <summary>
  19.            ''' All user sessions.
  20.            ''' </summary>
  21.            AllUsers = 2I
  22.  
  23.        End Enum
  24.  
  25.        ''' <summary>
  26.        ''' Adds an application to Windows Startup.
  27.        ''' </summary>
  28.        ''' <param name="User">Indicates the registry root key.</param>
  29.        ''' <param name="Title">Indicates the registry value name.</param>
  30.        ''' <param name="FilePath">Indicates the registry value data.</param>
  31.        Friend Shared Sub AddApplicationToWindowsStartup(ByVal User As User,
  32.                                                         ByVal Title As String,
  33.                                                         ByVal FilePath As String)
  34.  
  35.            Try
  36.                Select Case User
  37.  
  38.                    Case User.CurrentUser
  39.                        My.Computer.Registry.CurrentUser.
  40.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  41.                        SetValue(Title, FilePath, Microsoft.Win32.RegistryValueKind.String)
  42.  
  43.                    Case User.AllUsers
  44.                        My.Computer.Registry.LocalMachine.
  45.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  46.                        SetValue(Title, FilePath, Microsoft.Win32.RegistryValueKind.String)
  47.  
  48.                    Case Else
  49.                        Exit Select
  50.  
  51.                End Select
  52.  
  53.            Catch ex As Exception
  54.                Throw
  55.  
  56.            End Try
  57.  
  58.        End Sub
  59.  
  60.        ''' <summary>
  61.        ''' Removes an application from Windows Startup.
  62.        ''' </summary>
  63.        ''' <param name="User">Indicates the registry root key.</param>
  64.        ''' <param name="Title">Indicates the registry value name.</param>
  65.        Friend Shared Sub RemoveApplicationFromWindowsStartup(ByVal User As User,
  66.                                                              ByVal Title As String)
  67.            Try
  68.  
  69.                Select Case User
  70.  
  71.                    Case User.CurrentUser
  72.                        My.Computer.Registry.CurrentUser.
  73.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  74.                        DeleteValue(Title, throwOnMissingValue:=False)
  75.  
  76.                    Case User.AllUsers
  77.                        My.Computer.Registry.LocalMachine.
  78.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  79.                        DeleteValue(Title, throwOnMissingValue:=False)
  80.  
  81.                    Case Else
  82.                        Exit Select
  83.  
  84.                End Select
  85.  
  86.            Catch ex As Exception
  87.                Throw
  88.  
  89.            End Try
  90.  
  91.        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.

Código
  1.    ' Get x64 Process Path From x86
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.Management'
  6.    '
  7.    ' Usage Examples:
  8.    ' Dim path As String = GetX64ProcessPathFromX86("conhost.exe")
  9.    '
  10.    ''' <summary>
  11.    ''' Gets the process path of an x64 process from an x86 .NET application.
  12.    ''' </summary>
  13.    ''' <param name="ProcessName">Indicates the name of the process.</param>
  14.    ''' <returns>The process path.</returns>
  15.    Friend Shared Function GetX64ProcessPathFromX86(ByVal ProcessName As String) As String
  16.  
  17.        Dim wmiQuery As String = String.Format("SELECT ExecutablePath FROM Win32_Process Where Name = '{0}.exe'",
  18.                                               If(ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase),
  19.                                                  ProcessName.Remove(ProcessName.Length - ".exe".Length),
  20.                                                  ProcessName))
  21.  
  22.        Using searcher As New ManagementObjectSearcher(queryString:=wmiQuery)
  23.  
  24.            Using results As ManagementObjectCollection = searcher.[Get]
  25.  
  26.                If results.Count <> 0I Then
  27.  
  28.                    Return DirectCast(DirectCast(results(0I), ManagementBaseObject).
  29.                                      Properties("ExecutablePath").Value, String)
  30.  
  31.                Else
  32.                    Return String.Empty
  33.  
  34.                End If
  35.  
  36.            End Using
  37.  
  38.        End Using
  39.  
  40.    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:



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:

Código
  1. Public Class form1
  2.  
  3.    ''' <summary>
  4.    ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
  5.    ''' </summary>
  6.    Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}
  7.  
  8.    Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
  9.    Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
  10.  
  11.    Private Shadows Sub Load() Handles MyBase.Load
  12.  
  13.        ctrl_ElapsedTime = Label1
  14.        ctrl_RemainingTime = Label2
  15.  
  16.        Me.Clock.Start(60000) ' Measure 1 minute
  17.  
  18.        ' Or...
  19.        ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
  20.        ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
  21.        ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
  22.  
  23.    End Sub
  24.  
  25.    Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  26.    Handles Clock.ElapsedTimeUpdated
  27.  
  28.        ' Measure H:M:S:MS
  29.        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  30.                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  31.  
  32.    End Sub
  33.  
  34.    Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  35.    Handles Clock.RemainingTimeUpdated
  36.  
  37.        ' Measure H:M:S:MS
  38.        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  39.                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  40.  
  41.        '' Measure H:M:S
  42.        'ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  43.        '                                        e.Hour, e.Minute, e.Second + 1)
  44.  
  45.    End Sub
  46.  
  47.    Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  48.    Handles Clock.ElapsedTimeFinished
  49.  
  50.        ' Measure H:M:S:MS
  51.        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  52.                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  53.  
  54.    End Sub
  55.  
  56.    Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  57.    Handles Clock.RemainingTimeFinished
  58.  
  59.        ' Measure H:M:S:MS
  60.        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  61.                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  62.  
  63.    End Sub
  64.  
  65. 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:

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 10-02-2014
  4. ' ***********************************************************************
  5. ' <copyright file="TimeMeasurer.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class TimeMeasurer_Test
  13. '
  14. '    ''' <summary>
  15. '    ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
  16. '    ''' </summary>
  17. '    Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}
  18. '
  19. '    Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
  20. '    Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
  21. '
  22. '    Private Shadows Sub Load() Handles MyBase.Load
  23. '
  24. '        ctrl_ElapsedTime = LabelElapsed
  25. '        ctrl_RemainingTime = LabelRemaining
  26. '
  27. '        Me.Clock.Start(60000) ' Measure 1 minute
  28. '
  29. '        ' Or...
  30. '        ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
  31. '        ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
  32. '        ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
  33. '
  34. '    End Sub
  35. '
  36. '    ''' <summary>
  37. '    ''' Handles the ElapsedTimeUpdated event of the Clock instance.
  38. '    ''' </summary>
  39. '    ''' <param name="sender">The source of the event.</param>
  40. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  41. '    Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  42. '    Handles Clock.ElapsedTimeUpdated
  43. '
  44. '        ' Measure H:M:S:MS
  45. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  46. '                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  47. '
  48. '        ' Measure H:M:S
  49. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  50. '                                              e.Hour, e.Minute, e.Second)
  51. '
  52. '    End Sub
  53. '
  54. '    ''' <summary>
  55. '    ''' Handles the RemainingTimeUpdated event of the Clock instance.
  56. '    ''' </summary>
  57. '    ''' <param name="sender">The source of the event.</param>
  58. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  59. '    Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  60. '    Handles Clock.RemainingTimeUpdated
  61. '
  62. '        ' Measure H:M:S:MS
  63. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  64. '                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  65. '
  66. '        ' Measure H:M:S
  67. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  68. '                                                e.Hour, e.Minute, e.Second + 1)
  69. '
  70. '    End Sub
  71. '
  72. '    ''' <summary>
  73. '    ''' Handles the ElapsedTimeFinished event of the Clock instance.
  74. '    ''' </summary>
  75. '    ''' <param name="sender">The source of the event.</param>
  76. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  77. '    Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  78. '    Handles Clock.ElapsedTimeFinished
  79. '
  80. '        ' Measure H:M:S:MS
  81. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  82. '                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  83. '
  84. '        ' Measure H:M:S
  85. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  86. '                                              e.Hour, e.Minute, e.Second)
  87. '
  88. '    End Sub
  89. '
  90. '    ''' <summary>
  91. '    ''' Handles the RemainingTimeFinished event of the Clock instance.
  92. '    ''' </summary>
  93. '    ''' <param name="sender">The source of the event.</param>
  94. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  95. '    Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  96. '    Handles Clock.RemainingTimeFinished
  97. '
  98. '        ' Measure H:M:S:MS
  99. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  100. '                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  101. '
  102. '        ' Measure H:M:S
  103. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  104. '                                                e.Hour, e.Minute, e.Second)
  105. '
  106. '    End Sub
  107. '
  108. 'End Class
  109.  
  110. #End Region
  111.  
  112. #Region " Option Statements "
  113.  
  114. Option Strict On
  115. Option Explicit On
  116. Option Infer Off
  117.  
  118. #End Region
  119.  
  120. #Region " Imports "
  121.  
  122. Imports System.ComponentModel
  123.  
  124. #End Region
  125.  
  126. ''' <summary>
  127. ''' Measure a time interval.
  128. ''' This can be used as a chronometer or countdown timer.
  129. ''' </summary>
  130. Public NotInheritable Class TimeMeasurer
  131.  
  132. #Region " Objects "
  133.  
  134.    ''' <summary>
  135.    ''' <see cref="Stopwatch"/> instance to retrieve the elapsed time.
  136.    ''' </summary>
  137.    Private TimeElapsed As Stopwatch
  138.  
  139.    ''' <summary>
  140.    ''' <see cref="TimeSpan"/> instance to retrieve the remaining time.
  141.    ''' </summary>
  142.    Private TimeRemaining As TimeSpan
  143.  
  144.    ''' <summary>
  145.    ''' <see cref="Timer"/> instance that updates the elapsed and remaining times and raises the events.
  146.    ''' </summary>
  147.    Private WithEvents MeasureTimer As Timer
  148.  
  149.    ''' <summary>
  150.    ''' Indicates wheter the <see cref="TimeMeasurer"/> instance has finished to measure intervals.
  151.    ''' </summary>
  152.    Private IsFinished As Boolean
  153.  
  154. #End Region
  155.  
  156. #Region " Properties "
  157.  
  158.    ''' <summary>
  159.    ''' Gets the current state of this <see cref="TimeMeasurer"/> instance.
  160.    ''' </summary>
  161.    ''' <value>The update interval.</value>
  162.    Public ReadOnly Property State As TimeMeasurerState
  163.        Get
  164.            If Me.IsFinished Then
  165.                Return TimeMeasurerState.Finished
  166.  
  167.            ElseIf (Me.TimeElapsed Is Nothing) OrElse Not (Me.TimeElapsed.IsRunning) Then
  168.                Return TimeMeasurerState.Stopped
  169.  
  170.            Else
  171.                Return TimeMeasurerState.Running
  172.  
  173.            End If
  174.        End Get
  175.    End Property
  176.  
  177.    ''' <summary>
  178.    ''' Gets or sets the update interval.
  179.    ''' </summary>
  180.    ''' <value>The update interval.</value>
  181.    Public Property UpdateInterval As Integer
  182.        Get
  183.            Return Me._UpdateInterval
  184.        End Get
  185.        Set(ByVal value As Integer)
  186.            Me._UpdateInterval = value
  187.            If Me.MeasureTimer IsNot Nothing Then
  188.                Me.MeasureTimer.Interval = value
  189.            End If
  190.        End Set
  191.    End Property
  192.    ''' <summary>
  193.    ''' The update interval
  194.    ''' </summary>
  195.    Private _UpdateInterval As Integer = 100I
  196.  
  197. #End Region
  198.  
  199. #Region " Enumerations "
  200.  
  201.    ''' <summary>
  202.    ''' Specifies the current state of a <see cref="TimeMeasurer"/> instance.
  203.    ''' </summary>
  204.    <Description("Enum used as return value of 'State' property.")>
  205.    Public Enum TimeMeasurerState As Integer
  206.  
  207.        ''' <summary>
  208.        ''' The <see cref="TimeMeasurer"/> instance is running and measuring time intervals.
  209.        ''' </summary>
  210.        Running = 0I
  211.  
  212.        ''' <summary>
  213.        ''' The <see cref="TimeMeasurer"/> instance is temporally stopped, waiting to resume.
  214.        ''' </summary>
  215.        Stopped = 1I
  216.  
  217.        ''' <summary>
  218.        ''' The <see cref="TimeMeasurer"/> instance has finished to measure the time intervals.
  219.        ''' </summary>
  220.        Finished = 2I
  221.  
  222.    End Enum
  223.  
  224. #End Region
  225.  
  226. #Region " Events "
  227.  
  228.    ''' <summary>
  229.    ''' Occurs when the elapsed time updates.
  230.    ''' </summary>
  231.    Public Event ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  232.  
  233.    ''' <summary>
  234.    ''' Occurs when the remaining time updates.
  235.    ''' </summary>
  236.    Public Event RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  237.  
  238.    ''' <summary>
  239.    ''' Occurs when the elapsed time finishes.
  240.    ''' </summary>
  241.    Public Event ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  242.  
  243.    ''' <summary>
  244.    ''' Occurs when the elapsed time finishes.
  245.    ''' </summary>
  246.    Public Event RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  247.  
  248.    ''' <summary>
  249.    ''' Contains the <see cref="TimeMeasureEventArgs"/> arguments.
  250.    ''' </summary>
  251.    Public Class TimeMeasureEventArgs : Inherits EventArgs
  252.  
  253.        ''' <summary>
  254.        ''' Gets or sets the hour.
  255.        ''' </summary>
  256.        ''' <value>The hour.</value>
  257.        Public Property Hour As Double
  258.  
  259.        ''' <summary>
  260.        ''' Gets or sets the minute.
  261.        ''' </summary>
  262.        ''' <value>The minute.</value>
  263.        Public Property Minute As Double
  264.  
  265.        ''' <summary>
  266.        ''' Gets or sets the Second.
  267.        ''' </summary>
  268.        ''' <value>The Second.</value>
  269.        Public Property Second As Double
  270.  
  271.        ''' <summary>
  272.        ''' Gets or sets the Millisecond.
  273.        ''' </summary>
  274.        ''' <value>The Millisecond.</value>
  275.        Public Property Millisecond As Double
  276.  
  277.    End Class
  278.  
  279. #End Region
  280.  
  281. #Region " Public Methods "
  282.  
  283.    ''' <summary>
  284.    ''' Starts the time interval measurement from zero.
  285.    ''' </summary>
  286.    ''' <param name="Milliseconds">Indicates the time interval to measure, in milliseconds.</param>
  287.    Public Sub Start(ByVal Milliseconds As Double)
  288.  
  289.        If Milliseconds > (TimeSpan.MaxValue.TotalMilliseconds - 1001.0R) Then
  290.            Throw New ArgumentOutOfRangeException("Milliseconds",
  291.                                                  String.Format("The value can't be greater than {0}",
  292.                                                                CStr(TimeSpan.MaxValue.TotalMilliseconds - 1001.0R)))
  293.        End If
  294.  
  295.        Me.TimeElapsed = New Stopwatch
  296.        Me.TimeRemaining = TimeSpan.FromMilliseconds(Milliseconds)
  297.        Me.MeasureTimer = New Timer With
  298.           {
  299.             .Tag = Milliseconds,
  300.             .Interval = Me.UpdateInterval,
  301.             .Enabled = True
  302.           }
  303.  
  304.        Me.TimeElapsed.Start()
  305.        Me.MeasureTimer.Start()
  306.  
  307.    End Sub
  308.  
  309.    ''' <summary>
  310.    ''' Stops the time interval measurement.
  311.    ''' </summary>
  312.    Public Sub [Stop]()
  313.  
  314.        If (Me.MeasureTimer Is Nothing) OrElse Not (Me.TimeElapsed.IsRunning) Then
  315.            Throw New Exception("TimeMeasurer is not running.")
  316.  
  317.        Else
  318.            Me.MeasureTimer.Stop()
  319.            Me.TimeElapsed.Stop()
  320.  
  321.        End If
  322.  
  323.    End Sub
  324.  
  325.    ''' <summary>
  326.    ''' Resumes the time interval measurement.
  327.    ''' </summary>
  328.    Public Sub [Resume]()
  329.  
  330.        If (Me.MeasureTimer Is Nothing) OrElse (Me.TimeElapsed.IsRunning) Then
  331.            Throw New Exception("TimeMeasurer is not stopped.")
  332.  
  333.        Else
  334.            Me.MeasureTimer.Start()
  335.            Me.TimeElapsed.Start()
  336.  
  337.        End If
  338.  
  339.    End Sub
  340.  
  341. #End Region
  342.  
  343. #Region " Private Methods "
  344.  
  345.    ''' <summary>
  346.    ''' Stops Time intervals and resets the elapsed and remaining time to zero.
  347.    ''' </summary>
  348.    Private Sub Reset()
  349.  
  350.        Me.MeasureTimer.Stop()
  351.        Me.TimeElapsed.Reset()
  352.  
  353.    End Sub
  354.  
  355. #End Region
  356.  
  357. #Region " Event Handlers "
  358.  
  359.    ''' <summary>
  360.    ''' Handles the Tick event of the MeasureTimer control.
  361.    ''' </summary>
  362.    ''' <param name="sender">The source of the event.</param>
  363.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  364.    Private Sub MeasureTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  365.    Handles MeasureTimer.Tick
  366.  
  367.        Dim TimeDifference As TimeSpan = (Me.TimeRemaining - Me.TimeElapsed.Elapsed)
  368.        Dim ElapsedArgs As New TimeMeasureEventArgs
  369.        Dim RemainingArgs As New TimeMeasureEventArgs
  370.  
  371.        If (TimeDifference.TotalMilliseconds <= 0.0R) _
  372.        OrElse (Me.TimeElapsed.ElapsedMilliseconds > DirectCast(Me.MeasureTimer.Tag, Double)) Then
  373.  
  374.            Dim TotalTime As TimeSpan = TimeSpan.FromMilliseconds(DirectCast(Me.MeasureTimer.Tag, Double))
  375.  
  376.            With ElapsedArgs
  377.                .Hour = TotalTime.Hours
  378.                .Minute = TotalTime.Minutes
  379.                .Second = TotalTime.Seconds
  380.                .Millisecond = TotalTime.Milliseconds
  381.            End With
  382.  
  383.            With RemainingArgs
  384.                .Hour = 0.0R
  385.                .Minute = 0.0R
  386.                .Second = 0.0R
  387.                .Millisecond = 0.0R
  388.            End With
  389.  
  390.            Me.Reset()
  391.            Me.IsFinished = True
  392.            RaiseEvent ElapsedTimeFinished(Me.TimeElapsed, ElapsedArgs)
  393.            RaiseEvent RemainingTimeFinished(TimeDifference, RemainingArgs)
  394.  
  395.        Else
  396.  
  397.            With ElapsedArgs
  398.                .Hour = TimeElapsed.Elapsed.Hours
  399.                .Minute = TimeElapsed.Elapsed.Minutes
  400.                .Second = TimeElapsed.Elapsed.Seconds
  401.                .Millisecond = TimeElapsed.Elapsed.Milliseconds
  402.            End With
  403.  
  404.            With RemainingArgs
  405.                .Hour = Math.Floor(TimeDifference.TotalHours) Mod TimeSpan.MaxValue.TotalMilliseconds
  406.                .Minute = Math.Floor(TimeDifference.TotalMinutes) Mod 60.0R
  407.                .Second = Math.Floor(TimeDifference.TotalSeconds) Mod 60.0R
  408.                .Millisecond = Math.Floor(TimeDifference.TotalMilliseconds Mod 1000.0R)
  409.            End With
  410.  
  411.            RaiseEvent ElapsedTimeUpdated(Me.TimeElapsed, ElapsedArgs)
  412.            RaiseEvent RemainingTimeUpdated(TimeDifference, RemainingArgs)
  413.  
  414.        End If
  415.  
  416.    End Sub
  417.  
  418. #End Region
  419.  
  420. End Class
Páginas: 1 ... 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 [657] 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines