|
7001
|
Programación / .NET (C#, VB.NET, ASP) / Re: Crear una consola por hilo.
|
en: 12 Julio 2014, 21:16 pm
|
Una alternativa bastante sucia, dada la prohibición de adjuntar más de 1 consola por proceso, podría ser esta:
Por cada thread que inicies, ejecutas una CMD (instanciando la Class Process, nada de adjuntar mediante la WinAPI), y ya tendrías una consola "adjuntada" y distinta por cada thread, con todo el control necesario para escribir en el Buffer de cada una de ellas.
Saludos.
|
|
|
7002
|
Programación / .NET (C#, VB.NET, ASP) / Re: Duda con excepciones en .NET
|
en: 12 Julio 2014, 17:10 pm
|
Puedes obtener el nombre del método que lanzó la excepcion, utilizando la propiedad Exception.TargetSite. Gets the method that throws the current exception. Nota: Pero antes de pensar en usarlo para todas las circunstancias, deberías leer las "Remarks" del MSDN. Ejemplo de uso: Public Class Form1 Private Sub Test() Handles MyBase.Shown Try Me.Method1() Me.Method2() Catch ex As Exception MessageBox.Show(String.Format("Nombre del método: {0}", ex.TargetSite.Name)) End Try End Sub Private Sub Method1() Exit Sub Throw New InvalidOperationException End Sub Private Sub Method2() Throw New InvalidOperationException End Sub End Class
PD: También está disponible el nombre del método en el StackTrace, pero deberías parsear el String resultante, solo te lo comento como dato adicional porque sería una tontería hacer eso, ya que TargetSite obtiene el nombre desde el StackTrace, así que además si el StackTrace está vacío tampoco habrá un TargetSite accesible. Saludos.
|
|
|
7005
|
Programación / .NET (C#, VB.NET, ASP) / Re: Combinaciones numericas por posicion con numeros guias
|
en: 12 Julio 2014, 11:14 am
|
Como ya te expliqué sería mejor que te guiases por el código de antes y hacerle las modificaciones que resulten necesarias (lo digo por el nuevo post que has publicado con un código muy distinto), creo que tú entiendes mejor que yo el resultado que esperas obtener... Mira a ver si es esto lo que quieres: Establezco los números "guía" con sus números "asociados" (solo 20 guías), luego hago 80 combinaciones con los números "asociados" con una longitud de 6 números, y luego ordeno cada combinación de menor a mayor. Si algo de lo que acabo de comentar no es correcto, intenta ser específico. PD: Pueden darse combinaciones repetidas, pero una vez aclarado, en caso de que sea esto lo que buscas, entonces te diré como eliminar repetidas. Public Class ComboTest : Inherits Form #Region " Objects, Vars " ' La Class "Random", es necesaria para desordenar una colección ' y esta declaración tiene que ir siempre fuera de cualquier Sub. Private ComboRandomizer As New Random ' El control que creo en tiempo de ejecución, donde mostraré las combinaciones. Private rtb As New RichTextBox With { .Dock = DockStyle.Fill, .Font = New Font("Lucida Console", 10.0F) } ' Una "palanca" para habilitar/deshabilitar el bloque de depuración. Private EnableDebug As Boolean = False ' Instancio una lista donde iremos guardando cada combinación obtenida. Private Combos As New List(Of Integer()) ' Otra lista donde le daré el formato deseado a los números. Dim ComboStrings As List(Of String) = Nothing ' El máximo de combinaciones. Private Property MaxCombos As Integer = 80I ' El máximo de longitud para cada combinación. Private Property MaxComboLength As Integer = 6I ' Los números "guías" que usaremos para rellenar cada combinación. 'Private ReadOnly Numbers As Integer() = ' (From n As Integer In ' ("01-02-03-04-05-06-07-08-09-10-11-12-13-14-15-16-17-18-19-20-" & ' "21-22-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" ' ).Split({"-"}, StringSplitOptions.RemoveEmptyEntries)).ToArray ' Izquierda: Número "guía" ' Derecha: Número asociado Private ReadOnly NumberWheel As New Dictionary(Of Integer, Integer) From { {1, 21}, {2, 22}, {3, 23}, {4, 24}, {5, 25}, {6, 26}, {7, 27}, {8, 28}, {9, 29}, {10, 30}, {11, 31}, {12, 32}, {13, 33}, {14, 34}, {15, 35}, {16, 36}, {17, 37}, {18, 38}, {19, 39}, {20, 40} } #End Region #Region " Constructors " ' De este Sub no hagas caso, es el constructor del Form. Public Sub New() ' This call is required by the designer. ' Add any initialization after the InitializeComponent() call. InitializeComponent() With Me ' Seteo algunas propiedades sin imortancia. .Size = New Point(320, 480) .StartPosition = FormStartPosition.CenterScreen ' Añado el control al Form. .Controls.Add(rtb) End With End Sub #End Region #Region " Event-Handlers " Private Sub ComboTest() Handles MyBase.Shown Me.DoCombos() Me.PrintCombos() End Sub #End Region #Region " Methods " ' La función que se encarga de desordenar y devolverte una combinación. ' By Elektro. 'Friend Function GetRandomCombination(Of T)(ByVal [Collection] As IEnumerable(Of T), ' ByVal [Length] As Integer) As IEnumerable(Of T) ' Return (From Item As T In [Collection] ' Order By ComboRandomizer.Next ' Take [Length]).ToArray 'End Function [Length] As Integer) As IEnumerable(Of T) Return (From Item As KeyValuePair (Of T, T ) In [Collection] Select Item.Value Order By ComboRandomizer.Next Take [Length]).ToArray End Function Private Sub DoCombos() ' Añadir combinaciones a la lista, hasta que la lista tenga 'MaxComboLength' (80) elementos. Do Until Combos.Count = (MaxCombos - 1) ' Obtengo una combinación. Dim tmpCombo As Integer() = Me.GetRandomCombination(Of Integer)(NumberWheel, MaxComboLength) ' Ordeno los elementos de la combinación, de menos a mayor. Array.Sort(tmpCombo) ' Añado la combinación a la lista. Combos.Add(tmpCombo) Loop ' Ordeno los elementos de la lista, basandome en el orden de los elementos de cada Array. ' NOTA: Puede tener fallos al ordenar, no aseguro que el orden sea perfecto. Combos = (From Combo As Integer() In Combos Order By Convert.ToDecimal(String.Join("", Combo)) Ascending).ToList Combos = (From Combo As Integer() In Combos Order By Combo.First Ascending).ToList ' Además, creo utra lista Strings, para darle formato a cada combo numérico, ' y añadirle así un "0" a los números del "1" al "9" y que quede más bonito en la previsualización xD. Me.ComboStrings = (From Combo In Combos Select (String.Join(" | ", From Value As String In Combo Select If(Value.Length = 1, "0" & Value, Value)))).ToList ' El bloque de depuración. ' Este bloque entero es para testear el formato que le quieras dar. If Me.EnableDebug Then Dim sb As New System.Text.StringBuilder With sb For Index As Integer = 0 To (MaxCombos - 1) sb.AppendLine(String.Format("Combo sin formato:")) sb.AppendLine(String.Join(", ", Combos(Index))) sb.AppendLine() sb.AppendLine(String.Format("Combo con formato:")) sb.AppendLine(String.Join(", ", ComboStrings(Index))) MessageBox.Show(sb.ToString, "", MessageBoxButtons.OK, MessageBoxIcon.Information) sb.Clear() Next Index End With End If #End If End Sub Private Sub PrintCombos() ' Muestro los Combos en el control. With Me.rtb .SuspendLayout() For Each Combo As String In Me.ComboStrings .AppendText(Combo) .AppendText(Environment.NewLine & New String("-", Combo.Length) & Environment.NewLine) Next Combo .ResumeLayout() .Select(0, 0) End With End Sub #End Region End Class
|
|
|
7006
|
Programación / .NET (C#, VB.NET, ASP) / Re: Editar texto de un programa a partir de otro programa c#
|
en: 12 Julio 2014, 09:56 am
|
Si una aplicación no no puede interactuar de forma legítima con otro proceso (Sockets, Remote Object, etc...) cuando ese debería ser su proposito en este caso, entonces está mal desarrollada. Tu pregunta trata sobre un software que no ha sido desarrollado para la interacción entre procesos, y eso complica las cosas, la función sendmessage (enviando el message WM_GETTEXT) es algo que se inventó en el siglo pasado cuando las aplicaciones todavía no eran capaces de estar aisladas unas de las otras (cuando el término "isolation" no existía aún en lo referente a la programación de Software), pero en este siglo se debería evitar el uso de la WinAPI para hacer estas cosas, la verdad, al menos NO en caso de que los dos proyectos sean de tu propiedad y eso signifique que puedas editar los proyectos, entonces deberías escuchar la primera sugerencia de @KuBox para buscar otras soluciones. De todas formas si te empeñas en hacerlo usando la WinAPI (que tampoco es que sea algo malo, pero según se mire es una mala práctica), puedes empezar por buscar y escribir en tu código las declaraciones de todas estas funciones e informarte sobre el uso de ellas, así como el uso de los métodos de Marshal que te pondré al final que también te pueden servir como alternativa, y cuando lo tengas todo listo, ya podremos seguir hablando sobre el tema: · FindWindowEx function· WindowFromPoint function· GetClassName function· EnumChildWindows function· SendMessage function· WM_GETTEXT message· WM_GETTEXTLENGTH message· Marshal.AllocHGlobal Method· Marshal.PtrToStringUni MethodNota: Ten en cuenta que a cada Control de una aplicación se le asigna un Handle, pero además la zona vacía para escribir en ese Control segúramente tendrá otro Handle distinto. Nota 2: Lo he intentado, pero no he conseguido nada.. Al menos yo, al hablar sobre la WinAPI, mientras no muestres un código con tu progreso me limitaré solamente a ofrecerte información.
|
|
|
7007
|
Programación / Scripting / Re: indetectable
|
en: 11 Julio 2014, 14:06 pm
|
Los empaquetadores (conversores de "X" a "EXE"), sobre todo si son famosos pero sin buena reputación, suelen estar fichados por todos los antivirus como una "HackTool" o variantes de ese estilo, a pesar de que se usen con buenos fines ...por supuesto se conoce que otras muchas personas utilizan ese tipo de herramientas con fines ilegales. Puedes probar el Software ExeScript de ScriptCode.com, nunca me dió ese tipo de problemas con Bats ni Vbs's. De lo contrario, puedes intentar usar Themida o algún otro protector para indetectabilizar (en la medida de lo que sea posible) tu executable. Saludos.
|
|
|
7008
|
Programación / .NET (C#, VB.NET, ASP) / Re: Clickar a un color
|
en: 11 Julio 2014, 14:01 pm
|
Aquí os dejo una versión mejorada y extendida de lo anterior, por si a alguien le sirve: ' *********************************************************************** ' Author : Elektro ' Last Modified On : 07-11-2014 ' *********************************************************************** ' <copyright file="PixelUtil.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " ' ************************************************** ' Count the number of Pixels that contains the image ' ************************************************** ' '' Create a new bitmap. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False) ' '' Instance a PixelUtil Class. 'Dim bmpPixelUtil As New PixelUtil(bmp) ' '' Display the pixel count. 'MessageBox.Show(String.Format("Total amount of Pixels: {0}", CStr(bmpPixelUtil.PixelCount))) ' ************************************************ ' Searchs for an specific pixel color in the image ' ************************************************ ' '' Create a new bitmap. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False) ' '' Instance a PixelUtil Class. 'Dim bmpPixelUtil As New PixelUtil(bmp) ' '' Specify the RGB PixelColor to search. 'Dim FindColor As Color = Color.FromArgb(255, 174, 201) ' '' Get the pixel data. 'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.SearchColor(FindColor) ' '' Loop through each pixel. 'For Each Pixel As PixelUtil.PixelData In FoundPixels ' ' Dim sb As New System.Text.StringBuilder ' With sb ' ' .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index))) ' .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString)) ' ' MessageBox.Show(.ToString, "Pixel-Color Search") ' ' .Clear() ' ' End With ' 'Next Pixel ' ********************************************************************* ' Retrieve the index, color, and coordinates of each pixel in the image ' ********************************************************************* ' '' Create a new bitmap. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False) ' '' Instance a PixelUtil Class. 'Dim bmpPixelUtil As New PixelUtil(bmp) ' '' Get the pixel data. 'Dim Pixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData() ' '' Loop through each pixel. 'For Each Pixel As PixelUtil.PixelData In Pixels ' ' Dim sb As New System.Text.StringBuilder ' With sb ' ' .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index))) ' .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString)) ' .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString)) ' ' MessageBox.Show(.ToString, "Pixel Search") ' ' .Clear() ' ' End With ' 'Next Pixel ' **************************************************************************** ' Retrieve the index, color, and coordinates of a range of pixels in the image ' **************************************************************************** ' '' Create a new bitmap. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False) ' '' Instance a PixelUtil Class. 'Dim bmpPixelUtil As New PixelUtil(bmp) ' '' Specify the pixel range to retrieve. 'Dim RangeMin As Integer = 1919I 'Dim RangeMax As Integer = 1921I ' '' Get the pixel data. 'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData(RangeMin, RangeMax) ' '' Loop through each pixel. 'For Each Pixel As PixelUtil.PixelData In FoundPixels ' ' Dim sb As New System.Text.StringBuilder ' With sb ' ' .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index))) ' .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString)) ' .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString)) ' ' MessageBox.Show(.ToString, "Pixel-Color Search") ' ' .Clear() ' ' End With ' 'Next Pixel #End Region #Region " Imports " Imports System.ComponentModel Imports System.Drawing.Imaging Imports System.Runtime.InteropServices #End Region #Region " PixelUtil " Public Class PixelUtil #Region " Vars, Properties " Private _PixelData As List(Of PixelData) = Nothing Private _bmp As Bitmap = Nothing Private _PixelCount As Integer = Nothing ''' <summary> ''' Gets the Bitmap object. ''' </summary> ''' <value>The BMP.</value> Public ReadOnly Property bmp As Bitmap Get Return Me._bmp End Get End Property ''' <summary> ''' Gets the total amount of pixels that contains the Bitmap. ''' </summary> ''' <value>The pixel count.</value> Public ReadOnly Property PixelCount As Integer Get Return Me._PixelCount End Get End Property #End Region #Region " Classes " ''' <summary> ''' Stores specific pixel information of an image. ''' </summary> Public Class PixelData ''' <summary> ''' Gets or sets the pixel index. ''' </summary> ''' <value>The pixel index.</value> Public Property Index As Integer ''' <summary> ''' Gets or sets the pixel color. ''' </summary> ''' <value>The pixel color.</value> Public Property Color As Color ''' <summary> ''' Gets or sets the pixel coordinates relative to the image. ''' </summary> ''' <value>The pixel coordinates.</value> Public Property Coordinates As Point End Class #End Region #Region " Constructors " ''' <summary> ''' Prevents a default instance of the <see cref="PixelUtil"/> class from being created. ''' </summary> Private Sub New() End Sub ''' <summary> ''' Initializes a new instance of the <see cref="PixelUtil"/> class. ''' </summary> ''' <param name="bmp">Indicates the Bitmap image to process it's pixels.</param> ''' <exception cref="System.Exception">PixelFormat unsupported.</exception> Public Sub New(ByVal bmp As Bitmap) If Not bmp.PixelFormat = PixelFormat.Format24bppRgb Then Throw New Exception("PixelFormat unsupported.") End If Me._bmp = bmp Me._PixelCount = Me.[Count] End Sub #End Region #Region " Public Methods " ''' <summary> ''' Returns a <c>'PixelData'</c> object containing information about each pixel in the image. ''' </summary> ''' <returns>List(Of PixelData).</returns> Public Function GetPixelData() As List(Of PixelData) If Me._PixelData Is Nothing Then Me._PixelData = New List(Of PixelData) ' Lock the Bitmap bits. Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height) Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat) ' Get the address of the first line. Dim Pointer As IntPtr = bmpData.Scan0 ' Hold the bytes of the bitmap into a Byte-Array. ' NOTE: This code is specific to a bitmap with 24 bits per pixels. Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height) Dim rgbData(bmpBytes - 1) As Byte ' Copy the RGB values into the array. Marshal.Copy(Pointer, rgbData, 0, bmpBytes) ' Unlock the Bitmap bits. Me._bmp.UnlockBits(bmpData) ' Loop through each 24bpp-RGB value. For rgbIndex As Integer = 2 To rgbData.Length - 1 Step 3 ' Set the pixel Data. Dim Pixel As New PixelData With Pixel .Index = rgbIndex \ 3I .Color = Color.FromArgb(red:=rgbData(rgbIndex), green:=rgbData(rgbIndex - 1I), blue:=rgbData(rgbIndex - 2I)) .Coordinates = New Point(X:=(.Index Mod bmpRect.Width), Y:=(.Index - (.Index Mod bmpRect.Width)) \ bmpRect.Width) End With ' Add the PixelData into the list. Me._PixelData.Add(Pixel) Next rgbIndex End If Return Me._PixelData End Function ''' <summary> ''' Returns a <c>'PixelData'</c> object containing information about a range of pixels in the image. ''' </summary> ''' <returns>List(Of PixelData).</returns> ''' <exception cref="System.Exception">Pixel index is out of range</exception> Public Function GetPixelData(ByVal RangeMin As Integer, ByVal RangeMax As Integer) As List(Of PixelData) If Not (Me._PixelCount >= RangeMin AndAlso Me._PixelCount <= RangeMax) Then Throw New Exception("Pixel index is out of range.") Return Nothing End If ' Return the Pixel range. Return (From Pixel As PixelData In Me.GetPixelData() Where (Pixel.Index >= RangeMin AndAlso Pixel.Index <= RangeMax)).ToList End Function ''' <summary> ''' Searchs for the specified pixel-color inside the image and returns all the matches. ''' </summary> ''' <param name="PixelColor">Indicates the color to find.</param> ''' <returns>List(Of PixelData).</returns> Public Function SearchColor(ByVal PixelColor As Color) As List(Of PixelData) Return (From Pixel As PixelData In Me.GetPixelData Where Pixel.Color = PixelColor).ToList End Function #End Region #Region " Private Methods " ''' <summary> ''' Counts the number of pixels that contains the image. ''' </summary> ''' <returns>The number of pixels.</returns> Private Function [Count]() As Integer ' Lock the Bitmap bits. Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height) Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat) ' Get the address of the first line. Dim Pointer As IntPtr = bmpData.Scan0 ' Hold the bytes of the bitmap into a Byte-Array. ' NOTE: This code is specific to a bitmap with 24 bits per pixels. Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height) Dim rgbData(bmpBytes - 1) As Byte ' Copy the RGB values into the array. Marshal.Copy(Pointer, rgbData, 0, bmpBytes) ' Unlock the Bitmap bits. Me._bmp.UnlockBits(bmpData) Return rgbData.Count End Function #End Region #Region " Hidden Methods " ''' <summary> ''' Serves as a hash function for a particular type. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub GetHashCode() End Sub ''' <summary> ''' Determines whether the specified System.Object is equal to the current System.Object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub Equals() End Sub ''' <summary> ''' Returns a String that represents the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub ToString() End Sub #End Region End Class #End Region
|
|
|
7009
|
Programación / .NET (C#, VB.NET, ASP) / Re: Clickar a un color
|
en: 10 Julio 2014, 09:10 am
|
Te hago la mitad del trabajo, ahora, para ubicar las coordenadas relativas a la imagen por el momento no se me ocurre el modo de hacerlo, pero algo se podrá hacer obteniendo el índice del pixel encontrado (cosa que hago) usandola en alguna fórmula aritmética con el ancho y alto de la imagen. Public Class PixelData Public Index As Integer Public Color As Color Public Coordinates As Point End Class
Friend Function GetPixelData(ByVal bmp As Bitmap) As List(Of PixelData)
If Not bmp.PixelFormat = Imaging.PixelFormat.Format24bppRgb Then Throw New Exception("PixelFormat no soportado en esta función.") End If
' Lock the bitmap's bits. Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height) Dim bmpdata As Drawing.Imaging.BitmapData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat)
' Get the address of the first line. Dim ptr As IntPtr = bmpdata.Scan0
' Declare an array to hold the bytes of the bitmap. ' This code is specific to a bitmap with 24 bits per pixels. Dim bytes As Integer = Math.Abs(bmpdata.Stride) * bmp.Height Dim rgbValues(bytes - 1) As Byte
' Copy the RGB values into the array. Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
' Unlock the bits. bmp.UnlockBits(bmpdata)
' Set the Data to return. Dim Pixels As New List(Of PixelData)
' Loop through each 24bpp-RGB value. For Index As Integer = 2 To rgbValues.Length - 1 Step 3
Pixels.Add(New PixelData With { .Index = Index \ 3I, .Color = Color.FromArgb(rgbValues(Index), rgbValues(Index - 1I), rgbValues(Index - 2I)), .Coordinates = Point.Empty })
Next Index
Return Pixels
End FunctionEDITO: Fórmula encontrada. Nota: Lo he testeado con una imagen a resolución 2560x1600, el retorno de datos es practicamente instantaneo, la búsqueda puede variar según lo lejos que se encuentre el pixel en la iteración. ''' <summary> ''' Stores specific pixel information of an image. ''' </summary> Friend Class PixelData ''' <summary> ''' Gets or sets the pixel index. ''' </summary> ''' <value>The pixel index.</value> Public Property Index As Integer ''' <summary> ''' Gets or sets the pixel color. ''' </summary> ''' <value>The pixel color.</value> Public Property Color As Color ''' <summary> ''' Gets or sets the pixel coordinates relative to the image. ''' </summary> ''' <value>The pixel coordinates.</value> Public Property Coordinates As Point End Class ''' <summary> ''' Returns a <c>'PixelData'</c> object containing information about each pixel of an image. ''' </summary> ''' <param name="bmp">Indicates the Bitmap image to process.</param> ''' <returns>List(Of PixelData).</returns> ''' <exception cref="System.Exception">PixelFormat unsupported.</exception> Friend Function GetPixelData(ByVal bmp As Bitmap) As List(Of PixelData) If Not bmp.PixelFormat = Imaging.PixelFormat.Format24bppRgb Then Throw New Exception("PixelFormat unsupported.") End If ' Lock the Bitmap bits. Dim bmpRect As New Rectangle(0, 0, bmp.Width, bmp.Height) Dim bmpData As Drawing.Imaging.BitmapData = bmp.LockBits(bmpRect, Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat) ' Get the address of the first line. Dim Pointer As IntPtr = bmpData.Scan0 ' Hold the bytes of the bitmap into a Byte-Array. ' NOTE: This code is specific to a bitmap with 24 bits per pixels. Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height) Dim rgbData(bmpBytes - 1) As Byte ' Copy the RGB values into the array. Runtime.InteropServices.Marshal.Copy(Pointer, rgbData, 0, bmpBytes) ' Unlock the Bitmap bits. bmp.UnlockBits(bmpData) ' Instance the object to return. Dim Pixels As New List(Of PixelData) ' Loop through each 24bpp-RGB value. For rgbIndex As Integer = 2 To rgbData.Length - 1 Step 3 ' Get the pixel values. Dim PixelIndex As Integer = rgbIndex \ 3I Dim PixelCoordX As Integer = PixelIndex Mod bmpRect.Width Dim PixelCoordY As Integer = (PixelIndex - PixelCoordX) \ bmpRect.Width Dim PixelColorR As Short = rgbData(rgbIndex) Dim PixelColorG As Short = rgbData(rgbIndex - 1I) Dim PixelColorB As Short = rgbData(rgbIndex - 2I) ' Set the pixel Data. Dim Pixel As New PixelData With Pixel .Index = PixelIndex .Color = Color.FromArgb(PixelColorR, PixelColorG, PixelColorB) .Coordinates = New Point(PixelCoordX, PixelCoordY) End With ' Add the PixelData into the list. Pixels.Add(Pixel) Next rgbIndex Return Pixels End Function
Ejemplo de uso: Public Sub Test() Handles Button1.Click ' Create a new bitmap. Dim bmp As Bitmap = Bitmap.FromFile("Imagen de la pantalla.bmp", False) ' Specify the RGB PixelColor to search. Dim FindColor As Color = Color.FromArgb(255, 174, 201) ' Get the pixel data. Dim Pixels As List(Of PixelData) = Me.GetPixelData(bmp) ' Loop through each pixel. For Each Pixel As PixelData In Pixels If Pixel.Color.Equals(FindColor) Then Dim sb As New System.Text.StringBuilder With sb .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index))) .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString)) .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString)) MessageBox.Show(.ToString, "Pixel Search") .Clear() End With End If Next Pixel End Sub
Saludos
|
|
|
7010
|
Informática / Hardware / Re: ¿ Cooler bueno, económico, y silencioso para CPU AMD Socket AM3+ ?
|
en: 9 Julio 2014, 14:58 pm
|
Bueno, necesitaba una respuesta rápida (por miedo a que el problema fuese a mayores) y como no he podido obtener la ayuda que necesitaba, ya me respondo a mi mismo. Al final, basandome en los comentarios de varios productos, he decidido comprado un Cooler Master Hyper 212 EVO. Me podría haber permitido comprar un Cooler más caro, pero sin haber obtenido una opinión experta pues...tampoco voy a arriesgarme sin saber si hacia bien o mal, lo caro no siempre resulta mejor. PD: Si alquien quiere que le cuente mi experiencia sobre el producto, después de haberlo instalado, que lo comente y con gusto le describiré los detalles. Saludos!
|
|
|
|
|
|
|