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


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


  Mostrar Temas
Páginas: 1 ... 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 [38] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ... 107
371  Programación / Programación Visual Basic / MOVIDO: Problema con función Shell en VB.NET 2010 en: 22 Diciembre 2015, 02:06 am
El tema ha sido movido a .NET.

http://foro.elhacker.net/index.php?topic=445958.0
372  Foros Generales / Foro Libre / Regalo acceso de 48h. para http://uploaded.net/ en: 19 Diciembre 2015, 19:33 pm
Un año más vengo a hacerles esta pequeña, pequeñisima contribuición en forma de regalo navideño simplemente por ser miembros de este magnifico foro...

Vengo a regalar un cupón para acceder gratuitamente al servicio uploaded.net Premium durante 48 horas.

Para no generar ningún tipo de favoritismo u ofensa o cualquier otro conflicto similar por mi parte, se lo regalaré al primero que responda en este hilo incluyendo en su mensaje esta frase: "YO LO QUIERO".
( si lo pide con otras palabras entonces ignoraré la petición. )

Requisitos:
- Tener al menos un año de antiguedad en el foro.
- Tener más de 100 mensajes publicados (los mensajes del foro libre no cuentan).
- No pertenecer al Staff de elhacker.net (lo siento chicos, es un regalo para los usuarios :P)

Saludos!
373  Programación / .NET (C#, VB.NET, ASP) / [Source] Solución administrada para crear configuración portable en archivos INI en: 17 Diciembre 2015, 17:49 pm
.Net nos ofrece varias alternativas para guardar la configuración de usuario, cómo la serialización de datos, la infrastructura My.Settings, o recurrir al registro de windows, sin embargo, y al menos para mi, un archivo de inicialización (archivo.INI) sigue siendo la mejor forma para portabilizar la configuración de un software, ya que el formato es muy amistoso de cara al end-user (¿quien no sabe editar un INI?), es perfecto para desarrollar software portable y mantener la misma configuración de usuario al copiarlo de un PC a otro, así que he ideado este algoritmo en conjunción para la manipulación de archivos INI usando código administrado (un parser de cosecha propia, sin recurrir a código no administrado con las funciones de la API de Windows que leen archivos INI).

El resultado de todo esto es bastante código, un Type para representar una sección INI, otro Type para representar una llave de una sección INI, etc, pero solo es necesario copiar y pegar todo el código que he desarrollado, ya que su utilización es tan simple como lo que voy a mostrar a continuación...

Ejemplo de uso para crear un INI con una sección y un valor booleano:
Código
  1. Dim ini As New IniManager("C:\File.ini", Encoding.Default)
  2.  
  3. With ini
  4.  
  5.    .Clear()
  6.  
  7.    .Sections.Add("SectionName")
  8.    .Sections("SectionName").Keys.Add("KeyName", value:="", comment:="Commentary")
  9.    .Sections("SectionName").Keys("KeyName").Value = "True"
  10.  
  11.    .Save()
  12.  
  13. End With
  14.  
  15. Console.WriteLine(ini.ToString)



Para obtener el valor, lo hariamos así:
Código
  1. Dim setting As Boolean = CBool(ini.Sections("SectionName").Keys("KeyName").Value)

Tiene métodos de búsqueda de secciones y llaves, y demás.



IniSection, representa una sección INI:
http://pastebin.com/8mJUZ2Nb

IniKey, representa una llave INI:
http://pastebin.com/eE1ZSnFG

IniSectionCollection, representa una colección de secciones INI:
http://pastebin.com/jcFJ0yYd

IniKeyCollection, representa una colección de llaves INI:
http://pastebin.com/CLfBtB1h

IniManager, lo más importante, la class que administra de manera abstracta los Types mencionados para la manipulación de un archivo INI:
http://pastebin.com/xgy93Saq

Espero que a alguien más le sirva.

Saludos!
374  Foros Generales / Foro Libre / MOVIDO: Complejidad de un programa en: 17 Diciembre 2015, 16:55 pm
El tema ha sido movido a Programación General.

http://foro.elhacker.net/index.php?topic=445689.0
375  Programación / .NET (C#, VB.NET, ASP) / [SOURCE] Generar captchas para aplicaciones en: 15 Diciembre 2015, 13:24 pm
Buenas

Os dejo este sencillo y pequeño algoritmo para generar captchas para nuestras aplicaciones.

Se puede extender para añadir "ruido" en la imagen, o alterar la posición y la rotación de las letras, pero eso no lo he implementado ya que me parece algo excesivo para "autentificar" una simple aplicación de escritorio.

       
 
Modo de empleo:
Código
  1. Dim captcha As KeyValuePair(Of Bitmap, String) = GenerateCaptcha(length:=5, size:=PictureBox1.Size)
  2.  
  3. PictureBox1.BackgroundImage = captcha.Key
  4. Console.WriteLine(captcha.Value)

Código fuente:
Código
  1.    Dim rand As New Random
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' Generates a captcha image.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    ''' <example> This is a code example.
  9.    ''' <code>
  10.    ''' Dim captcha As KeyValuePair(Of Bitmap, String) = GenerateCaptcha(5, PictureBox1.ClientSize)
  11.    ''' PictureBox1.BackgroundImage = captcha.Key
  12.    ''' </code>
  13.    ''' </example>
  14.    ''' ----------------------------------------------------------------------------------------------------
  15.    ''' <param name="length">
  16.    ''' The character length.
  17.    ''' </param>
  18.    '''
  19.    ''' <param name="size">
  20.    ''' The image size.
  21.    ''' </param>
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <returns>
  24.    ''' A <see cref="KeyValuePair(Of Bitmap, String)"/> that contains the captcha image and the resulting string.
  25.    ''' </returns>
  26.    ''' ----------------------------------------------------------------------------------------------------
  27.    <DebuggerStepThrough>
  28.    Public Shared Function GenerateCaptcha(ByVal length As Integer,
  29.                                           ByVal size As Size) As KeyValuePair(Of Bitmap, String)
  30.  
  31.        Return GenerateCaptcha(length, size.Width, size.Height)
  32.  
  33.    End Function
  34.  
  35.    ''' ----------------------------------------------------------------------------------------------------
  36.    ''' <summary>
  37.    ''' Generates a captcha image.
  38.    ''' </summary>
  39.    ''' ----------------------------------------------------------------------------------------------------
  40.    ''' <example> This is a code example.
  41.    ''' <code>
  42.    ''' Dim captcha As KeyValuePair(Of Bitmap, String) = GenerateCaptcha(5, PictureBox1.Width, PictureBox1.Height)
  43.    ''' PictureBox1.BackgroundImage = captcha.Key
  44.    ''' </code>
  45.    ''' </example>
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    ''' <param name="length">
  48.    ''' The character length.
  49.    ''' </param>
  50.    '''
  51.    ''' <param name="width">
  52.    ''' The image width.
  53.    ''' </param>
  54.    '''
  55.    ''' <param name="height">
  56.    ''' The image height.
  57.    ''' </param>
  58.    ''' ----------------------------------------------------------------------------------------------------
  59.    ''' <returns>
  60.    ''' A <see cref="KeyValuePair(Of Bitmap, String)"/> that contains the captcha image and the resulting string.
  61.    ''' </returns>
  62.    ''' ----------------------------------------------------------------------------------------------------
  63.    <DebuggerStepThrough>
  64.    Public Shared Function GenerateCaptcha(ByVal length As Integer,
  65.                                           ByVal width As Integer,
  66.                                           ByVal height As Integer) As KeyValuePair(Of Bitmap, String)
  67.  
  68.        Dim captcha As New Bitmap(width, height)
  69.        Dim fontHeight As Integer = (height \ 2)
  70.        Dim vLineSpacing As Integer = 2
  71.        Dim hLineSpacing As Integer = 2
  72.        Dim str As String = String.Join("", (From c As Char In "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  73.                                     Order By rand.Next Select c).Take(length))
  74.  
  75.        Using g As Graphics = Graphics.FromImage(captcha)
  76.  
  77.            g.InterpolationMode = InterpolationMode.High
  78.            g.SmoothingMode = SmoothingMode.HighQuality
  79.            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit
  80.            g.CompositingQuality = CompositingQuality.HighQuality
  81.  
  82.            Using gradientBrush As New LinearGradientBrush(New Point(0, (height \ 2)),
  83.                                                           New Point(width, (height \ 2)),
  84.                                                           Color.FromArgb(rand.Next(&HFF7D7D7D, &HFFFFFFFF)),
  85.                                                           Color.FromArgb(rand.Next(&HFF7D7D7D, &HFFFFFFFF)))
  86.  
  87.                ' Draw gradient background.
  88.                g.FillRectangle(gradientBrush, New Rectangle(0, 0, width, height))
  89.  
  90.            End Using ' gradientBrush
  91.  
  92.            Using linesPen As New Pen(Brushes.Black, 1)
  93.  
  94.                ' Draw vertical lines.
  95.                For i As Integer = 1 To width
  96.                    Dim ptop As New Point(i * vLineSpacing, 0)
  97.                    Dim pBottom As New Point(i * vLineSpacing, height)
  98.                    g.DrawLine(linesPen, ptop, pBottom)
  99.                Next i
  100.  
  101.                ' Draw horizontal lines.
  102.                For i As Integer = 1 To height
  103.                    Dim ptop As New Point(0, i * hLineSpacing)
  104.                    Dim pBottom As New Point(width, i * hLineSpacing)
  105.                    g.DrawLine(linesPen, ptop, pBottom)
  106.                Next i
  107.  
  108.            End Using ' linesPen
  109.  
  110.            Using font As New Font("Arial", fontHeight)
  111.  
  112.                Using path As New GraphicsPath
  113.  
  114.                    For i As Integer = 0 To (str.Length - 1)
  115.  
  116.                        Dim charX As Integer =
  117.                            (((i * (width - (g.MeasureString(str(i), font, width).ToSize.Width \ length)))) \ length)
  118.  
  119.                        Dim charY As Integer = (height \ 2)
  120.  
  121.                        path.AddString(str(i), font.FontFamily, FontStyle.Bold, fontHeight,
  122.                                       New Point(charX, charY), New StringFormat With {.LineAlignment = StringAlignment.Center})
  123.  
  124.                    Next i
  125.  
  126.                    ' Draw characters.
  127.                    g.DrawPath(Pens.Black, path)
  128.                    g.FillPath(Brushes.Gainsboro, path)
  129.  
  130.                End Using
  131.  
  132.            End Using ' font
  133.  
  134.        End Using ' g
  135.  
  136.        Return New KeyValuePair(Of Bitmap, String)(captcha, str)
  137.  
  138.    End Function

Saludos
376  Programación / Programación C/C++ / Implementación de estructura C++ a C# en: 13 Diciembre 2015, 17:50 pm
Hola

Publico el tema aquí, por que creo que me podrá servir de más ayuda.

Estoy tratando de implementar la estructura DEVMODE en C#:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd183565%28v=vs.85%29.aspx
( y no me sirven las implementaciones de pinvoke.net u otros ejemplos online, ya que todas las que he visto hasta ahora son erroneas o desactualizadas en algún sentido )



He estado comparando los offsets en C++ y C#, en C++ con la macro offsetof y en C# con la función Marshal.OffsetOf, hasta llegar al miembro dmFields todo es correcto;
el problema que tengo, es que el offset del miembro dmColor es 60 en C++, mientras que en mi implementación es 68, esto quiere decir que mi implementación de los miembros de la primera union es incorrecta.

Según un experto en código no administrado, mi representación de las unions y el enfoque que le stoy dando es correcto, pero no debe ser del todo así, ya que las posiciones/offsets son distintas.

Código
  1.    [StructLayout(LayoutKind.Sequential)]
  2.    public struct DevMode {
  3.     private const int CchDeviceName = 32;
  4.     private const int CchFormName = 32;
  5.  
  6.     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CchDeviceName)]
  7.     public string DeviceName;
  8.     public short SpecVersion;
  9.     public short DriverVersion;
  10.     public short Size;
  11.     public short DriverExtra;
  12.     public DeviceModeFields Fields;
  13.     public UnionDevMode1 test1;
  14.     public short Color;
  15.     public short Duplex;
  16.     public short YResolution;
  17.     public short TTOption;
  18.     public short Collate;
  19.     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CchFormName)]
  20.     public string FormName;
  21.     public short LogPixels;
  22.     public int BitsPerPixel;
  23.     public int PixelsWidth;
  24.     public int PixelsHeight;
  25.     public UnionDevMode2 test2;
  26.     public int DisplayFrequency;
  27.     public int IcmMethod;
  28.     public int IcmIntent;
  29.     public int MediaType;
  30.     public int DitherType;
  31.     public int Reserved1;
  32.     public int Reserved2;
  33.     public int PanningWidth;
  34.     public int PanningHeight;
  35.    }
  36.  
  37.    [StructLayout(LayoutKind.Explicit)]
  38.    public struct UnionDevMode1 {
  39.     [FieldOffset(0)] public SubUnionDevMode1 subUnion1;
  40.     [FieldOffset(0)] public SubUnionDevMode2 subUnion2;
  41.    }
  42.  
  43.    [StructLayout(LayoutKind.Sequential)]
  44.    public struct SubUnionDevMode1 {
  45.     public short Orientation;
  46.     public short PaperSize;
  47.     public short PaperLength;
  48.     public short PaperWidth;
  49.     public short Scale;
  50.     public short Copies;
  51.     public short DefaultSource;
  52.     public short PrintQuality;
  53.    }
  54.  
  55.    [StructLayout(LayoutKind.Sequential)]
  56.    public struct SubUnionDevMode2 {
  57.     public Win32.Types.Point Position;
  58.     public DeviceModeDisplayOrientation DisplayOrientation;
  59.     public int DisplayFixedOutput;
  60.    }
  61.  
  62.    [StructLayout(LayoutKind.Explicit)]
  63.    public struct UnionDevMode2 {
  64.  
  65.     [FieldOffset(0)] public int DisplayFlags;
  66.     [FieldOffset(0)] public int Nup;
  67.  
  68.    }

El problema está en el miembro UnionDevMode1 , o al menos todo me indica eso, mejor dicho en alguno de los miembros de la estructura  SubUnionDevMode1 o  SubUnionDevMode2 , sin embargo, me he asegurado de que los types ocupan el mismo tamaño que en C++, vease:

POINTL = 8 bytes.
Win32.Types.Point = 8 bytes.

DeviceModeFields = int (4 bytes)
DeviceModeDisplayOrientation = int (4 bytes)

Teniendo esto en cuenta, ¿alguien es capaz de ver en lo que estoy fallando?.
377  Programación / Programación C/C++ / Offests de los miembros de la estructura DEVMODE en: 13 Diciembre 2015, 15:56 pm
Hola

Me gustaría saber si alguien con experiencia en C++ podría indicarme los offests de los miembros de la estructura DEVMODE:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd183565%28v=vs.85%29.aspx

Esto es por que estoy tratanto de trasladar las unions de dicha estructura a .Net, pero necesito saber los offsets de los miembros en C++ para comparar el resto de miembros, ya que algo hice mal, probablemente el tamaño de alguno de mis miembros declarados sea incorrecto en comparación con el tamaño definido en la estructura de C++.

Me han comentado que esto se hace con la macro offsetof:

Creo que no pido mucho, debe ser una cosa sencilla para quien maneje C++, pero si me equivoco disculpen y diganme más o menos como podría hacerlo yo mismo...

Saludos
378  Foros Generales / Foro Libre / Pregunta sobre gitaneo: ¿Cual es el nombre de esta artista? en: 9 Diciembre 2015, 18:54 pm
Pues eso, ¿alguien es capaz de reconocer la voz de esta cantante flamenca?:


Para ser sinceros llevo un buen rato buscando y nada... solo encontré muchas versiones distintas del mismo tema cantado por otros/as artistas.

La canción no me interesa, solo el nombre de la que canta el tema, pero por si sirve de algo es una versión del tema original de Mecano, "Una rosa es una rosa", del año 1991.

Saludos
379  Foros Generales / Foro Libre / Una duda muy offtopic sobre música cinemática... en: 7 Diciembre 2015, 19:06 pm
Buenas.

Siempre me he preguntado lo siguiente y espero poder resolver mi duda en este foro, por que nadie sabe nada respecto a esto...

Ahí va:



Si yo quisiera buscar temas parecidos a los temas de los videos de aquí abajo, ¿por qué estilo de música en concreto debería buscar?.

Ya todos lo sabrán pero para los que no lo sepan esta música se conoce comunmente como "música épica", pero eso no es un estilo ...no es nada de nada, es como quien dice que le gusta el "EDM" (música electrónica), que bien puede ser un tema hard-electro o una canción tecno-pop en Catalán, todo en el mismo saco y nada que ver, vaya. Por ese mismo motivo si me pongo a buscar por "música orquestral" o "sinfonias...¿?" o incluo "música épica" se que me va a salir todo tipo de música que la mayoría no se van a parecer en nada a estos temas de los videos, aparte, es que simplemente quiero saber el nombre de lo que estoy escuchando.

¿Alguien tiene mejor idea de que estilo de música es exactamente esto?. Y añado otra pregunta a ser posible que lo sepan, ¿conocen alguna página donde descargar solamente álbums de este estilo de música? (álbums comerciales o simplemente packs de temas sueltos de "música épica", vaya)

   

   

Otro ejemplo de lo que busco exactamente:
http://audiojungle.net/item/epic-music-pack-3/9768334

Típicas bandas sonoras en general, de películas y videojuegos "épicos"... jeje.

Saludos
380  Programación / .NET (C#, VB.NET, ASP) / [SOURCE] Añadir magnetismo a los bordes de una ventana/Form en: 1 Diciembre 2015, 22:14 pm
He estado refactorizando un viejo snippet, el cual es de mis favoritos, por ese motivo lo posteo aquí para hacer una mención especial y no en el apartado de snippets.

Lo que voy a mostrar es la forma más sencilla (copy&paste) para añadir magnetismo a una ventana.

Personalmente considero que todos deberiamos implementar esta funcionalidad en nuestras aplicaciones, ya que es una funcionalidad muy útil para mantener la organizción de las ventanas en la pantalla, cosa que cualquier usuario-final de su aplicación lo sabrá agradecer.

El magnetismo de ventanas consiste en que, al mover la ventana/Form cerca de un borde de la pantalla, la ventana se adhiera a dicho borde.



Nota: Esta funcionalidad estará incluida en la próxima versión de mi API ElektroKit: http://foro.elhacker.net/net/elektrokit_v10_api_de_proposito_general_para_desarrolladores_de_net-t444997.0.html



El siguiente código está escrito en Vb.Net (es suficiente con copiar, pegar y usar) pero se puede compilar en una dll para desarrolladores de código-C#.

La Class tiene dos propiedades importantes de personalización, la primera propiedad es WindowMagnetizer.Threshold, que indica el margen, en píxeles, en el que se debe producir el magnetismo. Yo suelo utilizar un valor de 35 píxeles ya que soy muy basto moviendo el ratón, pero creo que un valor de 20 seria lo apropiado de forma generalizada.

La otra propiedad se llama WindowMagnetizer.AllowOffscreen, que como su propio nombre indica por si mismo, sirve para habilitar o deshabilitar el poder mover la ventana fuera de los límites de la pantalla activa. (he tenido en cuenta la existencia de una pantalla dual).

El uso de esta class es muy, muy sencillo, tanto como esto:

Código
  1. Private magnetizer As New WindowMagnetizer(Me) With
  2.    {
  3.        .Enabled = True,
  4.        .AllowOffscreen = True,
  5.        .Threshold = 30
  6.    }

Código
  1. private WindowMagnetizer magnetizer;
  2.  
  3. private void Form1_Load(object sender, EventArgs e) {
  4.  
  5.   magnetizer = new WindowMagnetizer(this)
  6.                    {
  7.                        Enabled = true,
  8.                        AllowOffscreen = true,
  9.                        Threshold = 30
  10.                    };  
  11. }

Sin más, el código fuente:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 01-December-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Constructors "
  9.  
  10. ' WindowMagnetizer.New(IWin32Window)
  11.  
  12. #End Region
  13.  
  14. #Region " Properties "
  15.  
  16. ' WindowMagnetizer.Handle As IntPtr
  17. ' WindowMagnetizer.OwnerWindow As IWin32Window
  18. ' WindowMagnetizer.Threshold As Integer
  19. ' WindowMagnetizer.Enabled As Boolean
  20. ' WindowMagnetizer.AllowOffscreen As Boolean
  21.  
  22. #End Region
  23.  
  24. #Region " Methods "
  25.  
  26. ' WindowMagnetizer.Dispose()
  27.  
  28. #End Region
  29.  
  30. #End Region
  31.  
  32. #Region " Usage Examples "
  33.  
  34. 'Private magnetizer As New WindowMagnetizer(Me) With
  35. '    {
  36. '        .Enabled = True,
  37. '        .AllowOffscreen = True,
  38. '        .Threshold = 30
  39. '    }
  40.  
  41. #End Region
  42.  
  43. #Region " Option Statements "
  44.  
  45. Option Explicit On
  46. Option Strict On
  47. Option Infer Off
  48.  
  49. #End Region
  50.  
  51. #Region " Imports "
  52.  
  53. Imports System
  54. Imports System.ComponentModel
  55. Imports System.Drawing
  56. Imports System.Linq
  57. Imports System.Runtime.InteropServices
  58. Imports System.Windows.Forms
  59.  
  60. ' Imports Elektro.Interop.Win32
  61. ' Imports Elektro.Interop.Win32.Enums
  62. ' Imports Elektro.Interop.Win32.Types
  63.  
  64. #End Region
  65.  
  66. #Region " Window Magnetizer "
  67.  
  68.    ''' ----------------------------------------------------------------------------------------------------
  69.    ''' <summary>
  70.    ''' Add magnetism to the edges of a window,
  71.    ''' in this way, by bringing the window to a screen edge, the edge of the window adheres it to the edge of the screen.
  72.    ''' </summary>
  73.    ''' ----------------------------------------------------------------------------------------------------
  74.    ''' <example> This is a code example.
  75.    ''' <code>
  76.    ''' Private magnetizer As New WindowMagnetizer(Me) With
  77.    '''     {
  78.    '''         .Enabled = True,
  79.    '''         .AllowOffscreen = True,
  80.    '''         .Threshold = 30
  81.    '''     }
  82.    ''' </code>
  83.    ''' </example>
  84.    ''' ----------------------------------------------------------------------------------------------------
  85.    Public Class WindowMagnetizer : Inherits NativeWindow : Implements IDisposable
  86.  
  87. #Region " Private Fields "
  88.  
  89.        ''' ----------------------------------------------------------------------------------------------------
  90.        ''' <summary>
  91.        ''' Determines whether the owner window is being resized by one of its edges.
  92.        ''' </summary>
  93.        ''' ----------------------------------------------------------------------------------------------------
  94.        Protected isResizing As Boolean
  95.  
  96. #End Region
  97.  
  98. #Region " Properties "
  99.  
  100.        ''' ----------------------------------------------------------------------------------------------------
  101.        ''' <summary>
  102.        ''' Gets the window that owns this <see cref="WindowMagnetizer"/> instance.
  103.        ''' </summary>
  104.        ''' ----------------------------------------------------------------------------------------------------
  105.        ''' <value>
  106.        ''' The window.
  107.        ''' </value>
  108.        ''' ----------------------------------------------------------------------------------------------------
  109.        Public Overridable ReadOnly Property OwnerWindow As IWin32Window
  110.            <DebuggerStepThrough>
  111.            Get
  112.                Return Me.ownerWindowB
  113.            End Get
  114.        End Property
  115.        ''' ----------------------------------------------------------------------------------------------------
  116.        ''' <summary>
  117.        ''' ( Backing field )
  118.        ''' The window that owns this <see cref="WindowMagnetizer"/> instance.
  119.        ''' </summary>
  120.        ''' ----------------------------------------------------------------------------------------------------
  121.        Protected ownerWindowB As IWin32Window
  122.  
  123.        ''' ----------------------------------------------------------------------------------------------------
  124.        ''' <summary>
  125.        ''' Gets the handle for the window that owns this <see cref="WindowMagnetizer"/> instance.
  126.        ''' </summary>
  127.        ''' ----------------------------------------------------------------------------------------------------
  128.        ''' <value>
  129.        ''' The handle.
  130.        ''' </value>
  131.        ''' ----------------------------------------------------------------------------------------------------
  132.        Public Overridable Shadows ReadOnly Property Handle As IntPtr
  133.            <DebuggerStepThrough>
  134.            Get
  135.                Return MyBase.Handle
  136.            End Get
  137.        End Property
  138.  
  139.        ''' ----------------------------------------------------------------------------------------------------
  140.        ''' <summary>
  141.        ''' Gets or sets, in pixels, the minimum threshold that the magnetic window needs to dock it on the nearest window border.
  142.        ''' <para></para>
  143.        ''' (Default value is <c>20</c>))
  144.        ''' </summary>
  145.        ''' ----------------------------------------------------------------------------------------------------
  146.        ''' <value>
  147.        ''' The minimum threshold that the magnetic window needs to dock it on the nearest window border.
  148.        ''' </value>
  149.        ''' ----------------------------------------------------------------------------------------------------
  150.        Public Overridable Property Threshold As Integer
  151.            <DebuggerStepThrough>
  152.            Get
  153.                Return Me.thresholdB
  154.            End Get
  155.            <DebuggerStepThrough>
  156.            Set(ByVal value As Integer)
  157.                Me.thresholdB = value
  158.            End Set
  159.        End Property
  160.        ''' ----------------------------------------------------------------------------------------------------
  161.        ''' <summary>
  162.        ''' ( Backing field )
  163.        ''' The minimum threshold that the magnetic window needs to dock it on the nearest window border.
  164.        ''' </summary>
  165.        ''' ----------------------------------------------------------------------------------------------------
  166.        Protected thresholdB As Integer
  167.  
  168.        ''' ----------------------------------------------------------------------------------------------------
  169.        ''' <summary>
  170.        ''' Gets or sets a value indicating whether the magnetizer is enabled.
  171.        ''' </summary>
  172.        ''' ----------------------------------------------------------------------------------------------------
  173.        ''' <value>
  174.        ''' <see langword="True"/> if the magnetizer is enabled, otherwise, <see langword="False"/>.
  175.        ''' </value>
  176.        ''' ----------------------------------------------------------------------------------------------------
  177.        Public Overridable Property Enabled As Boolean
  178.            <DebuggerStepThrough>
  179.            Get
  180.                Return Me.enabledB
  181.            End Get
  182.            <DebuggerStepThrough>
  183.            Set(ByVal value As Boolean)
  184.                Me.enabledB = value
  185.            End Set
  186.        End Property
  187.        ''' ----------------------------------------------------------------------------------------------------
  188.        ''' <summary>
  189.        ''' ( Backing field )
  190.        ''' A value indicating whether the magnetizer is enabled.
  191.        ''' </summary>
  192.        ''' ----------------------------------------------------------------------------------------------------
  193.        Protected enabledB As Boolean
  194.  
  195.        ''' ----------------------------------------------------------------------------------------------------
  196.        ''' <summary>
  197.        ''' Gets or sets a value indicating whether the window can be moved off-screen.
  198.        ''' <para></para>
  199.        ''' Default value is <see langword="True"/>.
  200.        ''' </summary>
  201.        ''' ----------------------------------------------------------------------------------------------------
  202.        ''' <value>
  203.        ''' <see langword="True"/> if the window can be moved off-screen, otherwise, <see langword="False"/>.
  204.        ''' </value>
  205.        ''' ----------------------------------------------------------------------------------------------------
  206.        Public Overridable Property AllowOffscreen As Boolean
  207.            <DebuggerStepThrough>
  208.            Get
  209.                Return Me.allowOffscreenB
  210.            End Get
  211.            <DebuggerStepThrough>
  212.            Set(ByVal value As Boolean)
  213.                Me.allowOffscreenB = value
  214.            End Set
  215.        End Property
  216.        ''' ----------------------------------------------------------------------------------------------------
  217.        ''' <summary>
  218.        ''' ( Backing field )
  219.        ''' A value indicating whether the window can be moved off-screen.
  220.        ''' </summary>
  221.        ''' ----------------------------------------------------------------------------------------------------
  222.        Protected allowOffscreenB As Boolean
  223.  
  224. #End Region
  225.  
  226. #Region " Constructors "
  227.  
  228.        ''' ----------------------------------------------------------------------------------------------------
  229.        ''' <summary>
  230.        ''' Prevents a default instance of the <see cref="WindowMagnetizer"/> class from being created.
  231.        ''' </summary>
  232.        ''' ----------------------------------------------------------------------------------------------------
  233.        <DebuggerNonUserCode>
  234.        Private Sub New()
  235.        End Sub
  236.  
  237.        ''' ----------------------------------------------------------------------------------------------------
  238.        ''' <summary>
  239.        ''' Initializes a new instance of the <see cref="WindowMagnetizer"/> class.
  240.        ''' </summary>
  241.        ''' ----------------------------------------------------------------------------------------------------
  242.        ''' <param name="window">
  243.        ''' The <see cref="IWin32Window"/> window that owns this instance (eg. a <see cref="Form"/> window).
  244.        ''' </param>
  245.        ''' ----------------------------------------------------------------------------------------------------
  246.        <DebuggerStepThrough>
  247.        Public Sub New(ByVal window As IWin32Window)
  248.  
  249.            Me.allowOffscreenB = True
  250.            Me.thresholdB = 20
  251.            Me.ownerWindowB = window
  252.  
  253.            MyBase.AssignHandle(window.Handle)
  254.  
  255.        End Sub
  256.  
  257. #End Region
  258.  
  259. #Region " Private Methods "
  260.  
  261.        ''' ----------------------------------------------------------------------------------------------------
  262.        ''' <summary>
  263.        ''' If the margin between the specified <paramref name="window"/>
  264.        ''' and the nearest border of the active screeen is lower than the value specified in <paramref name="threshold"/>,
  265.        ''' then it docks the window to the border.
  266.        ''' </summary>
  267.        ''' ----------------------------------------------------------------------------------------------------
  268.        ''' <param name="window">
  269.        ''' The magnetic window.
  270.        ''' </param>
  271.        '''
  272.        ''' <param name="windowPosHandle">
  273.        ''' A pointer to a <see cref="Interop.Win32.Types.WindowPos"/> structure that contains the
  274.        ''' new size and position of the <paramref name="window"/>.
  275.        ''' </param>
  276.        '''
  277.        ''' <param name="threshold">
  278.        ''' The minimum threshold that the window needs to dock it on the nearest desktop border.
  279.        ''' </param>
  280.        ''' ----------------------------------------------------------------------------------------------------
  281.        Protected Overridable Sub DockToNearestScreenBorder(ByVal window As IWin32Window,
  282.                                                            ByVal windowPosHandle As IntPtr,
  283.                                                            Optional ByVal threshold As Integer = 0I)
  284.  
  285.            Dim workingArea As Rectangle =
  286.                Screen.FromControl(DirectCast(window, Control)).WorkingArea ' Active screen.
  287.  
  288.            workingArea.Width = 0
  289.            workingArea.Height = 0
  290.  
  291.            Screen.AllScreens.ToList.ForEach(
  292.                Sub(scr As Screen)
  293.                    workingArea.Width += scr.WorkingArea.Width
  294.                    workingArea.Height += scr.WorkingArea.Height
  295.                End Sub)
  296.  
  297.            Dim windowPos As WindowPos =
  298.                CType(Marshal.PtrToStructure(windowPosHandle, GetType(WindowPos)), WindowPos)
  299.  
  300.            If (windowPos.Y = 0) OrElse (windowPos.X = 0) Then
  301.                ' Nothing to do.
  302.                Exit Sub
  303.            End If
  304.  
  305.            Dim win32Rect As Rect
  306.            Dim rect As Rectangle
  307.            NativeMethods.GetWindowRect(window.Handle, win32Rect)
  308.            rect = win32Rect
  309.  
  310.            ' Top border
  311.            If ((windowPos.Y >= -threshold) AndAlso
  312.               ((workingArea.Y > 0) AndAlso (windowPos.Y <= (threshold + workingArea.Y)))) _
  313.            OrElse ((workingArea.Y <= 0) AndAlso (windowPos.Y <= threshold)) Then
  314.  
  315.                windowPos.Y = workingArea.Y
  316.  
  317.            End If
  318.  
  319.            ' Left border
  320.            If (windowPos.X >= (workingArea.X - threshold)) AndAlso
  321.               (windowPos.X <= (workingArea.X + threshold)) Then
  322.  
  323.                windowPos.X = workingArea.X
  324.  
  325.            ElseIf (windowPos.X <= (workingArea.X - threshold)) AndAlso
  326.                   Not (Me.allowOffscreenB) Then
  327.  
  328.                windowPos.X = workingArea.X
  329.  
  330.            End If
  331.  
  332.            ' Right border.
  333.            If ((windowPos.X + rect.Width) <= (workingArea.Right + threshold)) AndAlso
  334.               ((windowPos.X + rect.Width) >= (workingArea.Right - threshold)) Then
  335.  
  336.                windowPos.X = (workingArea.Right - rect.Width)
  337.  
  338.            ElseIf ((windowPos.X + rect.Width) >= (workingArea.Right + threshold)) AndAlso
  339.                   Not (Me.allowOffscreenB) Then
  340.  
  341.                windowPos.X = (workingArea.Right - rect.Width)
  342.  
  343.            End If
  344.  
  345.            ' Bottom border.
  346.            If ((windowPos.Y + rect.Height) <= (workingArea.Bottom + threshold)) AndAlso
  347.               ((windowPos.Y + rect.Height) >= (workingArea.Bottom - threshold)) Then
  348.  
  349.                windowPos.Y = (workingArea.Bottom - rect.Height)
  350.  
  351.            ElseIf ((windowPos.Y + rect.Height) >= (workingArea.Bottom + threshold)) AndAlso
  352.                   Not (Me.allowOffscreenB) Then
  353.  
  354.                windowPos.Y = (workingArea.Bottom - rect.Height)
  355.  
  356.            End If
  357.  
  358.            ' Marshal it back.
  359.            Marshal.StructureToPtr(structure:=windowPos, ptr:=windowPosHandle, fDeleteOld:=True)
  360.  
  361.        End Sub
  362.  
  363. #End Region
  364.  
  365. #Region " Window Procedure (WndProc) "
  366.  
  367.        ''' ----------------------------------------------------------------------------------------------------
  368.        ''' <summary>
  369.        ''' Invokes the default window procedure associated with this window to process windows messages.
  370.        ''' </summary>
  371.        ''' ----------------------------------------------------------------------------------------------------
  372.        ''' <param name="m">
  373.        ''' A <see cref="T:Message"/> that is associated with the current Windows message.
  374.        ''' </param>
  375.        ''' ----------------------------------------------------------------------------------------------------
  376.        <DebuggerStepThrough>
  377.        Protected Overrides Sub WndProc(ByRef m As Message)
  378.  
  379.            Select Case m.Msg
  380.  
  381.                Case WindowsMessages.WmSizing
  382.                    Me.isResizing = True
  383.  
  384.                Case WindowsMessages.WmExitSizeMove
  385.                    Me.isResizing = False
  386.  
  387.                Case WindowsMessages.WmWindowPosChanging
  388.  
  389.                    If Not (Me.isResizing) AndAlso (Me.enabledB) Then
  390.                        Me.DockToNearestScreenBorder(window:=Me.ownerWindowB,
  391.                                                     windowPosHandle:=m.LParam,
  392.                                                     threshold:=Me.thresholdB)
  393.                    End If
  394.  
  395.            End Select
  396.  
  397.            MyBase.WndProc(m)
  398.  
  399.        End Sub
  400.  
  401. #End Region
  402.  
  403. #Region " Hidden Base Members "
  404.  
  405.        <EditorBrowsable(EditorBrowsableState.Never)>
  406.        <DebuggerNonUserCode>
  407.        Public Shadows Function ReferenceEquals(ByVal objA As Object, ByVal objB As Object) As Boolean
  408.            Return Object.ReferenceEquals(objA, objB)
  409.        End Function
  410.  
  411.        <EditorBrowsable(EditorBrowsableState.Never)>
  412.        <DebuggerNonUserCode>
  413.        Public Shadows Function GetHashCode() As Integer
  414.            Return MyBase.GetHashCode
  415.        End Function
  416.  
  417.        <EditorBrowsable(EditorBrowsableState.Never)>
  418.        <DebuggerNonUserCode>
  419.        Public Shadows Function [GetType]() As Type
  420.            Return MyBase.GetType
  421.        End Function
  422.  
  423.        <EditorBrowsable(EditorBrowsableState.Never)>
  424.        <DebuggerNonUserCode>
  425.        Public Shadows Function Equals(ByVal obj As Object) As Boolean
  426.            Return MyBase.Equals(obj)
  427.        End Function
  428.  
  429.        <EditorBrowsable(EditorBrowsableState.Never)>
  430.        <DebuggerNonUserCode>
  431.        Public Shadows Function ToString() As String
  432.            Return MyBase.ToString
  433.        End Function
  434.  
  435.        <EditorBrowsable(EditorBrowsableState.Never)>
  436.        <DebuggerNonUserCode>
  437.        Public Shadows Sub AssignHandle(ByVal handle As IntPtr)
  438.            MyBase.AssignHandle(handle)
  439.        End Sub
  440.  
  441.        <EditorBrowsable(EditorBrowsableState.Never)>
  442.        <DebuggerNonUserCode>
  443.        Public Shadows Sub CreateHandle(ByVal cp As CreateParams)
  444.            MyBase.CreateHandle(cp)
  445.        End Sub
  446.  
  447.        <EditorBrowsable(EditorBrowsableState.Never)>
  448.        <DebuggerNonUserCode>
  449.        Public Shadows Sub DestroyHandle()
  450.            MyBase.DestroyHandle()
  451.        End Sub
  452.  
  453.        <EditorBrowsable(EditorBrowsableState.Never)>
  454.        <DebuggerNonUserCode>
  455.        Public Shadows Sub ReleaseHandle()
  456.            MyBase.ReleaseHandle()
  457.        End Sub
  458.  
  459.        <EditorBrowsable(EditorBrowsableState.Never)>
  460.        <DebuggerNonUserCode>
  461.        Public Shadows Function FromHandle(ByVal handle As IntPtr) As NativeWindow
  462.            Return NativeWindow.FromHandle(handle)
  463.        End Function
  464.  
  465.        <EditorBrowsable(EditorBrowsableState.Never)>
  466.        <DebuggerNonUserCode>
  467.        Public Shadows Function GetLifeTimeService() As Object
  468.            Return MyBase.GetLifetimeService
  469.        End Function
  470.  
  471.        <EditorBrowsable(EditorBrowsableState.Never)>
  472.        <DebuggerNonUserCode>
  473.        Public Shadows Function InitializeLifeTimeService() As Object
  474.            Return MyBase.InitializeLifetimeService
  475.        End Function
  476.  
  477.        <EditorBrowsable(EditorBrowsableState.Never)>
  478.        <DebuggerNonUserCode>
  479.        Public Shadows Function CreateObjRef(ByVal requestedType As Type) As System.Runtime.Remoting.ObjRef
  480.            Return MyBase.CreateObjRef(requestedType)
  481.        End Function
  482.  
  483.        <EditorBrowsable(EditorBrowsableState.Never)>
  484.        <DebuggerNonUserCode>
  485.        Public Shadows Sub DefWndProc(ByRef m As Message)
  486.            MyBase.DefWndProc(m)
  487.        End Sub
  488.  
  489. #End Region
  490.  
  491. #Region " IDisposable Implementation "
  492.  
  493.        ''' ----------------------------------------------------------------------------------------------------
  494.        ''' <summary>
  495.        ''' To detect redundant calls when disposing.
  496.        ''' </summary>
  497.        ''' ----------------------------------------------------------------------------------------------------
  498.        Protected isDisposed As Boolean
  499.  
  500.        ''' ----------------------------------------------------------------------------------------------------
  501.        ''' <summary>
  502.        ''' Releases all the resources used by this instance.
  503.        ''' </summary>
  504.        ''' ----------------------------------------------------------------------------------------------------
  505.        <DebuggerStepThrough>
  506.        Public Sub Dispose() Implements IDisposable.Dispose
  507.  
  508.            Me.Dispose(isDisposing:=True)
  509.            GC.SuppressFinalize(obj:=Me)
  510.  
  511.        End Sub
  512.  
  513.        ''' ----------------------------------------------------------------------------------------------------
  514.        ''' <summary>
  515.        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  516.        ''' Releases unmanaged and - optionally - managed resources.
  517.        ''' </summary>
  518.        ''' ----------------------------------------------------------------------------------------------------
  519.        ''' <param name="isDisposing">
  520.        ''' <see langword="True"/>  to release both managed and unmanaged resources;
  521.        ''' <see langword="False"/> to release only unmanaged resources.
  522.        ''' </param>
  523.        ''' ----------------------------------------------------------------------------------------------------
  524.        <DebuggerStepThrough>
  525.        Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)
  526.  
  527.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  528.  
  529.                With Me
  530.                    .enabledB = False
  531.                    .AllowOffscreen = True
  532.                    .thresholdB = 0
  533.                End With
  534.  
  535.                MyBase.ReleaseHandle()
  536.                MyBase.DestroyHandle()
  537.  
  538.            End If
  539.  
  540.            Me.isDisposed = True
  541.  
  542.        End Sub
  543.  
  544. #End Region
  545.  
  546.    End Class
  547.  
  548. #End Region

P/Invokes:

Código
  1.        <SuppressUnmanagedCodeSecurity>
  2.        <DllImport("user32.dll", SetLastError:=True)>
  3.        Public Shared Function GetWindowRect(ByVal hwnd As IntPtr,
  4.                                             ByRef rect As Rect
  5.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  6.        End Function



Código
  1. Public Enum WindowsMessages As Integer
  2.  
  3.        WmSizing = &H214
  4.        WmExitSizeMove = &H232
  5.        WmWindowPosChanging = &H46
  6.  
  7. End Enum


Código
  1. Imports System
  2. Imports System.Diagnostics
  3. Imports System.Linq
  4. Imports System.Runtime.InteropServices
  5.  
  6. #Region " Window Pos "
  7.  
  8.    ''' ----------------------------------------------------------------------------------------------------
  9.    ''' <summary>
  10.    ''' Contains information about the size and position of a window.
  11.    ''' </summary>
  12.    ''' ----------------------------------------------------------------------------------------------------
  13.    ''' <remarks>
  14.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms632612%28v=vs.85%29.aspx"/>
  15.    ''' </remarks>
  16.    ''' ----------------------------------------------------------------------------------------------------
  17.    <DebuggerStepThrough>
  18.    <StructLayout(LayoutKind.Sequential)>
  19.    Public Structure WindowPos
  20.  
  21. #Region " Fields "
  22.  
  23.        ''' <summary>
  24.        ''' A handle to the window.
  25.        ''' </summary>
  26.        Public Hwnd As IntPtr
  27.  
  28.        ''' <summary>
  29.        ''' The position of the window in Z order (front-to-back position).
  30.        ''' This member can be a handle to the window behind which this window is placed,
  31.        ''' or can be one of the special values listed with the 'SetWindowPos' function.
  32.        ''' </summary>
  33.        Public HwndInsertAfter As IntPtr
  34.  
  35.        ''' <summary>
  36.        ''' The position of the left edge of the window.
  37.        ''' </summary>
  38.        Public X As Integer
  39.  
  40.        ''' <summary>
  41.        ''' The position of the top edge of the window.
  42.        ''' </summary>
  43.        Public Y As Integer
  44.  
  45.        ''' <summary>
  46.        ''' The window width, in pixels.
  47.        ''' </summary>
  48.        Public Width As Integer
  49.  
  50.        ''' <summary>
  51.        ''' The window height, in pixels.
  52.        ''' </summary>
  53.        Public Height As Integer
  54.  
  55.        ''' <summary>
  56.        ''' Flag containing the window position.
  57.        ''' </summary>
  58.        Public Flags As Integer
  59.  
  60. #End Region
  61.  
  62.    End Structure
  63.  
  64. #End Region

Código
  1. Imports System
  2. Imports System.Diagnostics
  3. Imports System.Drawing
  4. Imports System.Linq
  5. Imports System.Runtime.InteropServices
  6.  
  7. #Region " Rect "
  8.  
  9.    ''' ----------------------------------------------------------------------------------------------------
  10.    ''' <summary>
  11.    ''' Defines the coordinates of the upper-left and lower-right corners of a rectangle.
  12.    ''' </summary>
  13.    ''' ----------------------------------------------------------------------------------------------------
  14.    ''' <remarks>
  15.    ''' <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd162897%28v=vs.85%29.aspx"/>
  16.    ''' <para></para>
  17.    ''' <see href="http://www.pinvoke.net/default.aspx/Structures/rect.html"/>
  18.    ''' </remarks>
  19.    ''' ----------------------------------------------------------------------------------------------------
  20.    <DebuggerStepThrough>
  21.    <StructLayout(LayoutKind.Sequential)>
  22.    Public Structure Rect
  23.  
  24. #Region " Properties "
  25.  
  26.        ''' ----------------------------------------------------------------------------------------------------
  27.        ''' <summary>
  28.        ''' Gets or sets the x-coordinate of the upper-left corner of the rectangle.
  29.        ''' </summary>
  30.        ''' ----------------------------------------------------------------------------------------------------
  31.        ''' <value>
  32.        ''' The x-coordinate of the upper-left corner of the rectangle.
  33.        ''' </value>
  34.        ''' ----------------------------------------------------------------------------------------------------
  35.        Public Property Left As Integer
  36.  
  37.        ''' ----------------------------------------------------------------------------------------------------
  38.        ''' <summary>
  39.        ''' Gets or sets the y-coordinate of the upper-left corner of the rectangle.
  40.        ''' </summary>
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        ''' <value>
  43.        ''' The y-coordinate of the upper-left corner of the rectangle.
  44.        ''' </value>
  45.        ''' ----------------------------------------------------------------------------------------------------
  46.        Public Property Top As Integer
  47.  
  48.        ''' ----------------------------------------------------------------------------------------------------
  49.        ''' <summary>
  50.        ''' Gets or sets the x-coordinate of the lower-right corner of the rectangle.
  51.        ''' </summary>
  52.        ''' ----------------------------------------------------------------------------------------------------
  53.        ''' <value>
  54.        ''' The x-coordinate of the lower-right corner of the rectangle.
  55.        ''' </value>
  56.        ''' ----------------------------------------------------------------------------------------------------
  57.        Public Property Right As Integer
  58.  
  59.        ''' ----------------------------------------------------------------------------------------------------
  60.        ''' <summary>
  61.        ''' Gets or sets the y-coordinate of the lower-right corner of the rectangle.
  62.        ''' </summary>
  63.        ''' ----------------------------------------------------------------------------------------------------
  64.        ''' <value>
  65.        ''' The y-coordinate of the lower-right corner of the rectangle.
  66.        ''' </value>
  67.        ''' ----------------------------------------------------------------------------------------------------
  68.        Public Property Bottom As Integer
  69.  
  70. #End Region
  71.  
  72. #Region " Constructors "
  73.  
  74.        ''' ----------------------------------------------------------------------------------------------------
  75.        ''' <summary>
  76.        ''' Initializes a new instance of the <see cref="Rect"/> struct.
  77.        ''' </summary>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        ''' <param name="left">
  80.        ''' The x-coordinate of the upper-left corner of the rectangle.
  81.        ''' </param>
  82.        '''
  83.        ''' <param name="top">
  84.        ''' The y-coordinate of the upper-left corner of the rectangle.
  85.        ''' </param>
  86.        '''
  87.        ''' <param name="right">
  88.        ''' The x-coordinate of the lower-right corner of the rectangle.
  89.        ''' </param>
  90.        '''
  91.        ''' <param name="bottom">
  92.        ''' The y-coordinate of the lower-right corner of the rectangle.
  93.        ''' </param>
  94.        ''' ----------------------------------------------------------------------------------------------------
  95.        Public Sub New(ByVal left As Integer,
  96.                       ByVal top As Integer,
  97.                       ByVal right As Integer,
  98.                       ByVal bottom As Integer)
  99.  
  100.            Me.Left = left
  101.            Me.Top = top
  102.            Me.Right = right
  103.            Me.Bottom = bottom
  104.  
  105.        End Sub
  106.  
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        ''' <summary>
  109.        ''' Initializes a new instance of the <see cref="Rect"/> struct.
  110.        ''' </summary>
  111.        ''' ----------------------------------------------------------------------------------------------------
  112.        ''' <param name="rect">
  113.        ''' The <see cref="Rectangle"/>.
  114.        ''' </param>
  115.        ''' ----------------------------------------------------------------------------------------------------
  116.        Public Sub New(ByVal rect As Rectangle)
  117.  
  118.            Me.New(rect.Left, rect.Top, rect.Right, rect.Bottom)
  119.  
  120.        End Sub
  121.  
  122. #End Region
  123.  
  124. #Region " Operator Conversions "
  125.  
  126.        ''' ----------------------------------------------------------------------------------------------------
  127.        ''' <summary>
  128.        ''' Performs an implicit conversion from <see cref="Rect"/> to <see cref="Rectangle"/>.
  129.        ''' </summary>
  130.        ''' ----------------------------------------------------------------------------------------------------
  131.        ''' <param name="rect">The <see cref="Rect"/>.
  132.        ''' </param>
  133.        ''' ----------------------------------------------------------------------------------------------------
  134.        ''' <returns>
  135.        ''' The resulting <see cref="Rectangle"/>.
  136.        ''' </returns>
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        Public Shared Widening Operator CType(rect As Rect) As Rectangle
  139.  
  140.            Return New Rectangle(rect.Left, rect.Top, (rect.Right - rect.Left), (rect.Bottom - rect.Top))
  141.  
  142.        End Operator
  143.  
  144.        ''' ----------------------------------------------------------------------------------------------------
  145.        ''' <summary>
  146.        ''' Performs an implicit conversion from <see cref="Rectangle"/> to <see cref="Rect"/>.
  147.        ''' </summary>
  148.        ''' ----------------------------------------------------------------------------------------------------
  149.        ''' <param name="rect">The <see cref="Rectangle"/>.
  150.        ''' </param>
  151.        ''' ----------------------------------------------------------------------------------------------------
  152.        ''' <returns>
  153.        ''' The resulting <see cref="Rect"/>.
  154.        ''' </returns>
  155.        ''' ----------------------------------------------------------------------------------------------------
  156.        Public Shared Widening Operator CType(rect As Rectangle) As Rect
  157.  
  158.            Return New Rect(rect)
  159.  
  160.        End Operator
  161.  
  162. #End Region
  163.  
  164.    End Structure
  165.  
  166. #End Region

Espero que esto les pueda servir de ayuda.

Saludos!
Páginas: 1 ... 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 [38] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ... 107
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines