Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Temas - Eleкtro

#766
Lo siento pero no se como se le llama a lo que pretendo hacer, así que le llamaré "easy-find" xD,

Esta listview tiene 4 columnas, y me gustaría que la listview se comportase de la siguiente manera con la columna nº 2 ("Archivo"):

- Al pulsar una tecla del teclado (una tecla del alfabeto), visualizar/seleccionar la primera línea que empiece por esa letra.

- (MENOS IMPORTANTE) > Si la columna está desordenada, la misma lógica pero seleccionar la línea más cercana empezando a buscar desde la linea seleccionada, HACIA ABAJO.

Imagino que costará un poco de trabajo así que no lo pido todo hecho, pero ayúdenme a empezar, lo del evento "OnKeyPress" es fácil de hacer, pero no sé como podría hacer el "easy-find"...


Para el primer problema he pensado en recorrer con un FOR todo el array de "ListView.Items()" para buscar el subitem que empiece por la letra presionada, pero de todas formas he preferido hacer este post por si saben de alguna manera más sencilla y/o rápida.

#767
¿Como puedo resolver esto en VB.NET?

EDITO:
Ups, pregunté demasiado rápido...

La solución:
Código (vbnet) [Seleccionar]
My.Resources.ResourceManager.GetObject(variable)


Código (vbnet) [Seleccionar]
   Public Sub LlamadaButton(ByVal sender As Object, ByVal e As System.EventArgs)
       Dim ButtonN As Button = CType(sender, Button)
       Dim ResourceName = ButtonN.Text
       ReadDelimitedText(My.Resources._(ResourceName), ";")     ' El problema: My.Resources._(ResourceName)
   End Sub


Error: Identifier expected
#768
Me gustaría manejar el mismo evento para una serie de botones, algo así:

Código (vbnet) [Seleccionar]
   Private Sub Buttons_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
       If Button1.IsClicked = True Then MsgBox("Se ha clickado el botón 1")
       If Button2.IsClicked = True Then MsgBox("Se ha clickado el botón 2")
       If Button3.IsClicked = True Then MsgBox("Se ha clickado el botón 3")
   End Sub


¿Es posible hacer eso?

Si no es posible...¿Que alternativas tengo para simplificarlo de alguna manera parecida, sin tener que hacer un sub por cada evento ".Click" de cada Botón?

Gracias.
#769
.NET (C#, VB.NET, ASP) / Property Viewer
5 Enero 2013, 16:33 PM
¿Donde puedo descargar un buen property viewer?

Algo parecido a esto:



En especial ví uno muy bueno con una interfaz sencilla y un dialogo para cargar cualquier DLL dentro del programa y testear sus propiedades en tiempo real,
por ejemplo abres un control DLL que contiene un botón, en el property viewer, y puedes cambiar las propiedades del color en tiempo real...

Por desgracia perdí la aplicación :(.


#770
Hola, necesito ayuda con mi programa que tarda unos 10 seg. en visualizarse el form principal, y se carga antes el notifyicon que el form con unos segundos de diferencia xD  ¿Eso es normal?

Antes tardaba incluso más en cargar, pero he mejorado el tiempo de carga ejecutando el sub importante un nuevo thread.

En el form load solo hago 4 estúpidas compbocaciones y lo importante corre en un thread separado, por eso pienso que no debería tardar tanto en mostrarse el form...

¿Que puede ser?, ¿Ven algo extraño en el form load?

Bueno, voy a intentar dar datos útiles:



Proyecto: Windows form
Form: double buffered
Framework: 4.0
Controles de terceros: un GroupPanel con degradado, un dialogo de carpetas, y una barra de progreso. (La barra de progreso está visible por defecto.)
Recursos que tiene que cargar el exe: 3 dll's que pesan en total 5 MB. están separados, aunque también comparé la velocidad unificandolo con .NET shrink y el resultado es el mismo.
Prefetch de windows: Desactivado (No pienso activarlo para solucionar el problema)


El proyecto entero:
http://www.mediafire.com/?zije2zggdmv669t

Como podeis ver, es una app sencilla, pero aparte de que tarda en iniciarse, me consumía muchos muchos recursos, si no le libero memória como hago en el form antes consumía 40 mb después de iniciarse SIN TOCAR NADA, ni con dispose lo arreglaba, ahora solo consume 4-5 mb, pero digo que eso es extraño...

El form principal:
Código (vbnet) [Seleccionar]
Public Class Form1

#Region "Declarations"

   Dim filesystem As Object
   Dim ThisDir As Object
   Dim mcheck(0) As CheckBox
   Dim labelnum = 0
   Public Shared playerargs As String
   Public Shared Temp_file As String = System.IO.Path.GetTempPath & "\PlayDir_tmp.m3u"

   ' Checkboxes Thread
   Public checkboxes_thread As System.Threading.Thread = New Threading.Thread(AddressOf updatecheckboxes)

   ' Select all Thread
   Public select_all_thread As System.Threading.Thread = New Threading.Thread(AddressOf Select_or_unselect_all)

   ' Randomize thread
   Public Thread_is_completed As Boolean = False
   Public Want_to_abort_thread As Boolean = False
   Public Want_to_cancel_thread As Boolean = False

   ' Flush memory
   Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal process As IntPtr, ByVal minimumWorkingSetSize As Integer, ByVal maximumWorkingSetSize As Integer) As Integer

#End Region

#Region "Properties"

   'userSelectedPlayerFilePath
   Public Property userSelectedPlayerFilePath() As String
       Get
           Return Textbox_Player.Text
       End Get
       Set(value As String)
           Textbox_Player.Text = value
       End Set
   End Property

   ' userSelectedFolderPath
   Public Property userSelectedFolderPath() As String
       Get
           Return Textbox_Folder.Text
       End Get
       Set(value As String)
           Textbox_Folder.Text = value
       End Set
   End Property

#End Region

#Region "Load / Close"

   ' Form load
   Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

       If Not My.Computer.FileSystem.DirectoryExists(My.Settings.folderpath) Then
           My.Settings.folderpath = Nothing
           ProgressBar.Visible = False
           Me.Size = New System.Drawing.Size(Me.Width, 240)
           Panel_Folders.Size = New System.Drawing.Size(0, 0)
           Checkbox_SelectAll.Enabled = False
       Else
           Checkbox_SelectAll.Enabled = True
           Textbox_Folder.Text = My.Settings.folderpath
           ProgressBar.Visible = True
       End If

       If Not My.Computer.FileSystem.FileExists(My.Settings.playerpath) Then
           My.Settings.playerpath = Nothing
       Else
           Textbox_Player.Text = My.Settings.playerpath
       End If

       If My.Settings.randomize = True Then Checkbox_Randomize.Checked = True
       If My.Settings.autoclose = True Then Checkbox_AutoClose.Checked = True

       Updatecheckboxes_Start()

       My.Settings.Save()

   End Sub

   ' Form close
   Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
       Want_to_abort_thread = True

       SyncLock thread_1 'ensures all other threads running stop
           thread_1.Abort()
       End SyncLock

       If Not My.Settings.folderpath = Nothing Then
           GenerarPropiedades()
       End If

       My.Settings.Save()

       NotifyIcon1.Visible = False
       NotifyIcon1.Dispose()

   End Sub

#End Region

#Region "Save / Get settings"

   ' Generate properties
   Public Sub GenerarPropiedades()

       Dim mCheckados(0) As Int32
       Dim Cuantos As Int32 = 0
       Dim empty = Nothing

       Try
           For Each c As CheckBox In Panel_Folders.Controls
               empty = False
           Next

           If Not empty = False Then
               My.Settings.Valores = Nothing
           Else
               For i As Int32 = 0 To mcheck.Length - 1
                   If mcheck(i).Checked = True Then
                       Cuantos += 1
                       Array.Resize(mCheckados, Cuantos)
                       mCheckados(Cuantos - 1) = i + 1
                   End If
               Next
               My.Settings.Valores = mCheckados
           End If
       Catch
       End Try

   End Sub

   ' Load properties
   Public Sub CargarPropiedades()
       If My.Settings.Valores IsNot Nothing Then
           For Each indiceCheckado As Int32 In My.Settings.Valores()
               If Not indiceCheckado = 0 Then
                   InvokeControl(mcheck(indiceCheckado - 1), Sub(x) x.Checked = True)
               End If
           Next
       End If
   End Sub

#End Region

#Region "Checkboxes"

   ' Checkbox thread start
   Private Sub Updatecheckboxes_Start()
       checkboxes_thread.Abort()
       checkboxes_thread = New Threading.Thread(AddressOf updatecheckboxes)
       checkboxes_thread.IsBackground = False
       checkboxes_thread.Start()
   End Sub

   ' Checkbox thread
   Public Sub updatecheckboxes()

       If Not My.Settings.folderpath Is Nothing Then

           InvokeControl(Checkbox_SelectAll, Sub(x) x.Enabled = False)
           InvokeControl(Checkbox_SelectAll, Sub(x) x.Checked = False)
           InvokeControl(Button_PLAY, Sub(x) x.Enabled = False)
           InvokeControl(Button_PLAY, Sub(x) x.BackColor = Color.FromArgb(50, 50, 50))
           InvokeControl(Panel_Folders, Sub(x) x.Enabled = False)
           InvokeControl(ProgressBar, Sub(x) x.TextFormat = "Sorting folders, please wait...")
           InvokeControl(ProgressBar, Sub(x) x.TextShow = ProgBar.ProgBarPlus.eTextShow.FormatString)

           ' delete the old checkboxes
           InvokeControl(Panel_Folders, Sub(x) x.Controls.Clear())

           ' create the new checkboxes
           Dim filesystem = CreateObject("Scripting.FileSystemObject")
           Dim ThisDir = filesystem.GetFolder(My.Settings.folderpath)
           Dim i As Int32 = 0
           Dim pos As Int32 = 5
           For Each folder In ThisDir.Subfolders
               Array.Resize(mcheck, i + 1)
               mcheck(i) = New CheckBox
               With mcheck(i)
                   .BackColor = Color.Transparent
                   .ForeColor = Color.White
                   .AutoSize = False
                   .Size = New Point(338, 20)
                   .Location = New Point(1, pos)
                   .Name = "CheckBox" & i + 1
                   .Text = folder.Name
                   .Cursor = Cursors.Hand
               End With
               InvokeControl(Panel_Folders, Sub(x) x.Controls.Add(mcheck(i)))
               AddHandler mcheck(i).CheckedChanged, AddressOf LlamadaCheckBox
               i += 1
               pos += 20
           Next

           ' Load checked checkboxes
           CargarPropiedades()

           ' Reset saved checked checkboxes
           My.Settings.Valores = Nothing

           InvokeControl(ProgressBar, Sub(x) x.TextShow = ProgBar.ProgBarPlus.eTextShow.None)
           InvokeControl(ProgressBar, Sub(x) x.TextFormat = "Sorting files... {1}% Done")
           InvokeControl(Panel_Folders, Sub(x) x.Enabled = True)
           InvokeControl(Button_PLAY, Sub(x) x.Enabled = True)
           InvokeControl(Button_PLAY, Sub(x) x.BackColor = Color.SteelBlue)
           InvokeControl(Checkbox_SelectAll, Sub(x) x.Enabled = True)
           InvokeControl(Panel_Folders, Sub(x) x.Focus())

       End If

       FlushMemory("PlayDir")
   End Sub

   ' Checkbox events
   Public Sub LlamadaCheckBox(ByVal sender As Object, ByVal e As System.EventArgs)
       Dim filesystem = CreateObject("Scripting.FileSystemObject")
       Dim ThisDir = filesystem.GetFolder(My.Settings.folderpath)
       Dim CheckboxN As CheckBox = CType(sender, CheckBox)

       If CheckboxN.Checked = True Then
           labelnum += 1
           playerargs = playerargs & " " & ControlChars.Quote & System.IO.Path.Combine(ThisDir.Path, CheckboxN.Text.ToString()) & ControlChars.Quote
       Else
           labelnum -= 1
           playerargs = Replace(playerargs, " " & ControlChars.Quote & System.IO.Path.Combine(ThisDir.Path, CheckboxN.Text.ToString()) & ControlChars.Quote, "")
       End If

       If labelnum < 0 Then
           labelnum = 0
           InvokeControl(Label_SelectedFolders, Sub(x) x.Text = "0 folders selected")
       Else
           InvokeControl(Label_SelectedFolders, Sub(x) x.Text = labelnum & " folders selected")
       End If

   End Sub

#End Region

#Region "Buttons"

   ' Folder button
   Public Sub Button_SearchFolder_Click(sender As Object, e As EventArgs) Handles Button_SearchFolder.Click
       Dim folderselect As New Ookii.Dialogs.VistaFolderBrowserDialog
       folderselect.ShowNewFolderButton = True
       If folderselect.ShowDialog.ToString() = "OK" Then
           My.Settings.Valores = Nothing
           labelnum = 0
           Label_SelectedFolders.Text = labelnum & " folders selected"
           userSelectedFolderPath = folderselect.SelectedPath
           My.Settings.folderpath = folderselect.SelectedPath
           My.Settings.Save()
           playerargs = Nothing
           Me.Size = New System.Drawing.Size(400, 550)
           Panel_Folders.Size = New System.Drawing.Size(360, 250)
           ProgressBar.Visible = True
           Updatecheckboxes_Start()
       End If
   End Sub

   ' Player button
   Public Sub Button_SearchPlayer_Click(sender As Object, e As EventArgs) Handles Button_SearchPlayer.Click
       Dim playerselected As New OpenFileDialog()
       playerselected.InitialDirectory = Environ("programfiles")
       playerselected.Title = "Select your favorite music player"
       playerselected.Filter = "Music players|bsplayer.exe;mpc.exe;mpc-hc.exe;mpc-hc64.exe;umplayer.exe;vlc.exe;winamp.exe;wmp.exe"
       PlayerDialog.FilterIndex = 1
       Dim selection As System.Windows.Forms.DialogResult = playerselected.ShowDialog()
       If selection = DialogResult.OK Then
           userSelectedPlayerFilePath = playerselected.FileName
           My.Settings.playerpath = playerselected.FileName
           My.Settings.Save()
       End If
       FlushMemory("PlayDir")
   End Sub

   ' Refresh button
   Private Sub Button_Refresh_Click(sender As Object, e As EventArgs) Handles Button_Refresh.Click
       labelnum = 0
       Label_SelectedFolders.Text = "0 folders selected"
       Updatecheckboxes_Start()
   End Sub

   ' Play button
   Public Sub Button_PLAY_Click(sender As Object, e As EventArgs) Handles Button_PLAY.Click
       Me.Focus()

       If Button_PLAY.Tag = "Cancel" Then
           Want_to_cancel_thread = True
           Want_to_abort_thread = True
           While Not Thread_is_completed = True
               Application.DoEvents()
           End While
           ProgressBar.ResetBar()
           ProgressBar.Max = 100
           ProgressBar.Value = 0
       Else
           If Not System.IO.File.Exists(Textbox_Player.Text) Then
               MessageBox.Show("You need to select a music player...", "PlayDir", MessageBoxButtons.OK, MessageBoxIcon.Error)
           Else
               If Not playerargs = Nothing Then
                   Checkbox_Randomize.Enabled = False
                   Checkbox_SelectAll.Enabled = False
                   Button_PLAY.Image = My.Resources.Cancel_button
                   Button_PLAY.Tag = "Cancel"
                   Button_PLAY.BackColor = Color.Red
                   ProgressBar.Max = 100
                   ProgressBar.TextShow = ProgBar.ProgBarPlus.eTextShow.FormatString
                   If Checkbox_Randomize.Checked = True Then
                       Thread_is_completed = False
                       Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
                       thread_1.IsBackground = True
                       thread_1.Start()
                       While Not Thread_is_completed = True
                           Application.DoEvents()
                       End While
                   Else
                       If Not thread_1.ThreadState = Threading.ThreadState.AbortRequested Or Want_to_abort_thread = True Or Want_to_cancel_thread = True Then
                           Process.Start(userSelectedPlayerFilePath, playerargs)
                       End If
                   End If
                   If Checkbox_AutoClose.Checked = True And Not Want_to_cancel_thread = True Then Me.Close()
               Else
                   If Textbox_Player.Text = "Select a music player..." Then MessageBox.Show("You need to select a music player...", "PlayDir", MessageBoxButtons.OK, MessageBoxIcon.Error)
                   If Textbox_Folder.Text = "Select a folder..." Then MessageBox.Show("You need to open a folder with music files...", "PlayDir", MessageBoxButtons.OK, MessageBoxIcon.Error)
                   MessageBox.Show("You need to select at least one folder...", "PlayDir", MessageBoxButtons.OK, MessageBoxIcon.Stop)
               End If
           End If
           Want_to_abort_thread = False
           Want_to_cancel_thread = False
           Button_PLAY.Image = My.Resources.Play
           Button_PLAY.Tag = "Play"
           Button_PLAY.BackColor = Color.SteelBlue
           ProgressBar.TextShow = ProgBar.ProgBarPlus.eTextShow.None
           Panel_Folders.Focus()
           Checkbox_Randomize.Enabled = True
           Checkbox_SelectAll.Enabled = True
           FlushMemory("PlayDir")
       End If
   End Sub

   ' Auto-close
   Public Sub Checkbox_AutoClose_CheckedChanged(sender As Object, e As EventArgs) Handles Checkbox_AutoClose.CheckedChanged
       If Checkbox_AutoClose.Checked = True Then
           Picturebox_AutoClose.Visible = True
           My.Settings.autoclose = True
       Else
           Picturebox_AutoClose.Visible = False
           My.Settings.autoclose = False
       End If
       Panel_Folders.Focus()
       My.Settings.Save()
   End Sub

   ' Randomize
   Public Sub Checkbox_Randomize_CheckedChanged(sender As Object, e As EventArgs) Handles Checkbox_Randomize.CheckedChanged
       If Checkbox_Randomize.Checked = True Then
           Picturebox_Randomize.Visible = True
           My.Settings.randomize = True
       Else
           Picturebox_Randomize.Visible = False
           My.Settings.randomize = False
       End If
       Panel_Folders.Focus()
       My.Settings.Save()
   End Sub

   ' Select  ALL checkboxes
   Public Sub Checkbox_SelectAll_CheckedChanged(sender As Object, e As EventArgs) Handles Checkbox_SelectAll.CheckedChanged
       select_all_thread.Abort()
       select_all_thread = New Threading.Thread(AddressOf Select_or_unselect_all)
       select_all_thread.IsBackground = True
       select_all_thread.Start()
       Panel_Folders.Focus()
   End Sub

   Private Sub Select_or_unselect_all()
       CheckForIllegalCrossThreadCalls = False
       If Checkbox_SelectAll.Checked = False Then

           InvokeControl(Picturebox_SelectAll, Sub(x) x.Visible = False)
           InvokeControl(Checkbox_SelectAll, Sub(x) x.Text = "Select all")

           For Each ControlName In Panel_Folders.Controls
               ControlName.Checked = False
           Next

       Else

           InvokeControl(Picturebox_SelectAll, Sub(x) x.Visible = True)
           InvokeControl(Checkbox_SelectAll, Sub(x) x.Text = "Select none")

           For Each ControlName In Panel_Folders.Controls
               ControlName.Checked = True
           Next

       End If
       CheckForIllegalCrossThreadCalls = True
       FlushMemory("PlayDir")
   End Sub

#End Region

#Region "Drag & Drop"

   Private Sub Textboxes_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Textbox_Folder.DragDrop, Panel_Folders.DragDrop
       If e.Data.GetDataPresent(DataFormats.FileDrop) Then
           Dim Objetos As String() = e.Data.GetData(DataFormats.FileDrop)
           Dim attributes = Objetos(0)
           If System.IO.Directory.Exists(attributes) Then
               Textbox_Folder.Text = Objetos(0)
               userSelectedFolderPath = Objetos(0)
               My.Settings.folderpath = Objetos(0)
               My.Settings.Save()
               playerargs = Nothing
               Me.Size = New System.Drawing.Size(400, 540)
               Panel_Folders.Size = New System.Drawing.Size(360, 250)
               labelnum = 0
               Label_SelectedFolders.Text = "0 folders selected"
               Updatecheckboxes_Start()
           Else
               MessageBox.Show("Invalid directory!", "PlayDir", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
           End If
       End If
   End Sub

   Private Sub Textboxes_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Textbox_Folder.DragEnter, Panel_Folders.DragEnter
       If e.Data.GetDataPresent(DataFormats.FileDrop) Then
           e.Effect = DragDropEffects.All
       End If
   End Sub

#End Region

#Region " Notify icon "

   ' Form resize
   Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
       If Me.WindowState = FormWindowState.Minimized Then
           Me.WindowState = FormWindowState.Normal
           Me.Hide()
       End If
       FlushMemory("PlayDir")
   End Sub

   ' Double click
   Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
       If Me.Visible = True Then
           Me.Hide()
       Else
           Me.Show()
       End If
       FlushMemory("PlayDir")
   End Sub

   ' right click
   Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
       If e.Button = MouseButtons.Right Then NotifyIcon1.ContextMenuStrip.Show()
       FlushMemory("PlayDir")
   End Sub

   ' Mostrar
   Private Sub MostrarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ContextMenuStrip1.Click
       Me.Show()
       FlushMemory("PlayDir")
   End Sub

   ' Ocultar
   Private Sub OcultarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles Ocultar.Click
       Me.Hide()
       FlushMemory("PlayDir")
   End Sub

   ' Salir
   Private Sub SalirToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles Salir.Click
       Me.Close()
   End Sub

#End Region

#Region " Tooltip events "

   Private Sub SuperTooltip_TooltipClosed(sender As Object, e As EventArgs) Handles SuperTooltip1.TooltipClosed
       FlushMemory("PlayDir")
   End Sub

#End Region

#Region " Randomize Thread "

   Public thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)

   Public Sub mithread()

       Dim Str As String
       Dim Pattern As String = ControlChars.Quote
       Dim ArgsArray() As String
       Str = Replace(playerargs, " " & ControlChars.Quote, "")
       ArgsArray = Split(Str, Pattern)
       Using objWriter As New System.IO.StreamWriter(Temp_file, False, System.Text.Encoding.UTF8)
           Dim n As Integer = 0
           Dim count As Integer = 0
           Dim foldercount As Integer = -1

           For Each folder In ArgsArray
               foldercount += 1
               If foldercount > 1 Then
                   InvokeControl(ProgressBar, Sub(x) x.Max = foldercount)
               End If
           Next

           If foldercount = 1 Then
               For Each folder In ArgsArray
                   If Not folder = Nothing Then
                       Dim di As New IO.DirectoryInfo(folder)
                       Dim files As IO.FileInfo() = di.GetFiles("*")
                       Dim file As IO.FileInfo
                       InvokeControl(ProgressBar, Sub(x) x.Max = files.Count)
                       For Each file In files
                           If Want_to_abort_thread = False And Want_to_cancel_thread = False Then
                               n += 1
                               CheckPrimeNumber(n)
                               count += 1
                               If file.Extension.ToLower = ".lnk" Then
                                   Dim ShotcutTarget As String = Shortcut.ResolveShortcut((file.FullName).ToString())
                                   objWriter.Write(ShotcutTarget & vbCrLf)
                               Else
                                   objWriter.Write(file.FullName & vbCrLf)
                               End If
                           Else
                               Exit For
                           End If
                       Next
                   End If
               Next

           ElseIf foldercount > 1 Then
               For Each folder In ArgsArray
                   If Not folder = Nothing Then
                       Dim di As New IO.DirectoryInfo(folder)
                       Dim files As IO.FileInfo() = di.GetFiles("*")
                       Dim file As IO.FileInfo
                       For Each file In files
                           If Want_to_abort_thread = False And Want_to_cancel_thread = False Then
                               If file.Extension.ToLower = ".lnk" Then
                                   Dim ShotcutTarget As String = Shortcut.ResolveShortcut((file.FullName).ToString())
                                   objWriter.Write(ShotcutTarget & vbCrLf)
                               Else
                                   objWriter.Write(file.FullName & vbCrLf)
                               End If
                           Else
                               Exit For
                           End If
                       Next
                   End If
                   InvokeControl(ProgressBar, Sub(x) x.Value += 1)
               Next
           End If
       End Using

       If Not thread_1.ThreadState = Threading.ThreadState.AbortRequested And Not Want_to_abort_thread = True And Not Want_to_cancel_thread = True Then
           Randomize_a_file.RandomizeFile(Temp_file)
           InvokeControl(ProgressBar, Sub(x) x.Value = 0)
           Try
               Process.Start(userSelectedPlayerFilePath, ControlChars.Quote & Temp_file.ToString() & ControlChars.Quote)
           Catch
           End Try
       End If
       Thread_is_completed = True
   End Sub

#End Region

#Region " Check prime number function "
   Private Sub CheckPrimeNumber(ByVal number As Integer)
       Dim IsPrime As Boolean = True
       For i = 2 To number / 2
           If (number Mod i = 0) Then
               IsPrime = False
               Exit For
           End If
       Next i
       If IsPrime = True Then
           InvokeControl(ProgressBar, Sub(x) x.Value = number)
       End If
   End Sub
#End Region

#Region " InvokeControl "

   Public Sub InvokeControl(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T))
       If Not Want_to_abort_thread = True Then
           Try
               If Control.InvokeRequired Then
                   Control.Invoke(New Action(Of T, Action(Of T))(AddressOf InvokeControl), New Object() {Control, Action})
               Else
                   Action(Control)
               End If
           Catch
           End Try
       End If
   End Sub
#End Region

#Region "Flush memory"

   Public Sub FlushMemory(process_to_flush)
       Try
           GC.Collect()
           GC.WaitForPendingFinalizers()
           If (Environment.OSVersion.Platform = PlatformID.Win32NT) Then
               SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1)
               Dim myProcesses As Process() = Process.GetProcessesByName(process_to_flush)
               Dim myProcess As Process
               For Each myProcess In myProcesses
                   SetProcessWorkingSetSize(myProcess.Handle, -1, -1)
               Next myProcess
           End If
       Catch
       End Try
   End Sub

#End Region

End Class


#771
Quiero hacer esos "selectores" de números, con sus botones de subir/bajar a la derecha igual que en esta imagen:



¿Que control necesito usar?

Una vez lo intenté hacer con un ComboBox y haciendo uso del system.windows.time, pero me salió como el culo :laugh:, toda la info que encontré es para hacer un "TimePicker", pero no es lo mismo :-/

¿Hay algún control nativo o extendido que esté pensado para eso?

Un saludo!
#772
Quiero compilar este control para que el archivo resultante séa una dll, así de sencillo  :-\.

Lo intento creando un nuevo proyecto de tipo "class library" como me dijo Seba123Neo, el problema es que no me encuentra el "Listview" en el inherits...

He intentado importar algo sin tener conocimiento de si debo importar algo primero,
He buscado como hacerlo en Google,
He descargado listviews extendidas para ver que le falta a este código (Ni idea),
... Lo he intentado, ¿Vale? xD

Código (vbnet) [Seleccionar]
Public Class Listview_Unflickered

      Inherits ListView

      Public Sub New()
          MyBase.New()
          ' This bypass the flashing effect when adding items into the Listview
          Me.DoubleBuffered = True
      End Sub

  End Class
#773
¿Le ven alguna mejora al diseño de la aplicación?





Los botones quizás sond emasiado grandes, pero lo que más me preocupa es el panel de opciones, que cada vez se hace más grande (más opciones nuevas que añadir...) y ya no se donde meterlo ni como ajustarlo de tamaño y posición, a mi no me convence mucho como está ahora mismo. ¿Le ven alguna solución a eso?

PD: No quiero usar pestañas, por eso... xD.
#774
¿Me pueden decir alguna manera sencilla para ordenar alfabéticamente la columna de "problem" al pulsar click sobre el nombre de la columna?

O al menos, ¿Como se llama el evento que debo manejar? :S

Gracias.

#775
Cuando añado un item al listrview, hace un flash, un efecto muy desagradable.

Lo he intentado TODO, AddRange, Suspendlayout, Me.Doublebuffered, y por último BeginUpdate... Nada lo ha resuelto.

Código (vbnet) [Seleccionar]

for each file....

               Problems += 1
               str(0) = Problems
               str(1) = str(1).Substring(2)
               str(2) = File.FullName
               itm = New ListViewItem(str)
               InvokeControl(ListView, Sub(x) x.BeginUpdate())
               InvokeControl(ListView, Sub(x) x.Items.Add(itm))
               InvokeControl(ListView, Sub(x) x.EnsureVisible(ListView.Items.Count - 1))
               InvokeControl(ListView, Sub(x) x.EndUpdate())
end for...


Esto es otra variante del código, aquí noto cierta mejora (Flashes más cortos):
Código (vbnet) [Seleccionar]

  Private Sub AddItemToListView()
       str(0) = Problems
       str(1) = str(1).Substring(2)
       str(2) = File.FullName
       itm = New ListViewItem(str)
       ListView.SuspendLayout()
       InvokeControl(ListView, Sub(x) x.BeginUpdate())
       InvokeControl(ListView, Sub(x) x.Items.Add(itm))
       InvokeControl(ListView, Sub(x) x.EnsureVisible(ListView.Items.Count - 1))
       InvokeControl(ListView, Sub(x) x.EndUpdate())
       ListView.ResumeLayout()
       If NumberIsOdd(Problems) Then
           itm.BackColor = Color.FromArgb(15, 15, 15)
       Else
           itm.BackColor = Color.FromArgb(30, 30, 30)
       End If
   End Sub




Sé que el AddRange y BeginUpdate están pensados para añadir varios items, pero como podeis comprobar en el ejemplo es que yo necesito añadirlos uno por uno.

¿Que puedo hacer?
#776
Necesito terminar la ejecución de mi APP con un "End",
Todos sabemos que si matamos una aplicación, el icono del SystemTray se queda en memoria, es decir, seguirá visible...
Pero por otro lado imagino que se debe poder eliminar el icono del systray en tiempo de ejecución, antes de matar indebídamente la APP, para que eso no suceda.

¿Como puedo eliminar el NotifyIcon?

Código (vbnet) [Seleccionar]
   ' Close
   Private Sub Form_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
       Worker.Dispose() ' Liberar los recursos del BackgroundWorker

       ' Eliminar la visibilidad del SysTrayMenu antes de matar la APP, para que no se quede visible en el SystemTray...
       SystrayMenu.Visible = False
       SystrayMenu.Dispose()

       End ' Matar todo lo relacionado con la APP
   End Sub


EDITO: Ups, con las prisas no me dí cuenta, había confundido el nombre del menú con otro menú que tengo en la APP,
Tema solucionado XD
#777
He arrastrado una imagen a la carpeta "Resources" (Dentro de la IDE), pero cuando intento aplicarla a una propiedad, no reconoce la imagen, es como si no existiera...

La imagen se llama "OpenDir.png", pero esto no puedo hacerlo, porque no me la encuentra:
Código (vbnet) [Seleccionar]
ContextMenu_Open_Dir.Image = My.Resources.OpenDir


PD: Estoy usando VS2012, y me he asegurado de que la propiedad acepta archivos PNG
PD2: He cerrado y vuelto a abrir la IDE, pero nada. . . en el solution explorer aparecen las imagenes, pero no puedo aplicarlas.

¿Que me falta por hacer? xD
#778
El problema es que selecciono varias líneas, abro un menú contextual, hago click en la opción deseada pero el contenido de la variable "FileInformation" siempre es el mismo valor, si selecciono 5 líneas pues el valor es siempre el de la primera línea...
¿Estoy usando mal el índice?

EDITO: se me olvidaba comentar que se trata de un listview con 2 columnas y yo intento mostrar el item de la segunda columna. La opción de seleccionar la "row" entera está activada.

Código (vbnet) [Seleccionar]
   Private Sub NewMenu_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles NewMenu.ItemClicked
       Dim FileInformation = Nothing
       If e.ClickedItem.Name = "OpenDir" Then
           For Each Entry In ListView1.SelectedItems()
               FileInformation = My.Computer.FileSystem.GetFileInfo(ListView1.SelectedItems(0).SubItems(1).Text)
               MsgBox("explorer.exe" & " /select," & FileInformation.DirectoryName & "\" & FileInformation.Name)
               'Process.Start("explorer.exe", " /select," & FileInformation.DirectoryName & "\" & FileInformation.Name)
               FileInformation = Nothing
           Next
       End If



En cambio esto me funciona perféctamente:

Código (vbnet) [Seleccionar]
       If e.ClickedItem.Name = "DeleteEntry" Then
           For Each Entry In ListView1.SelectedItems()
               ListView1.Items.Remove(ListView1.SelectedItems(0))
           Next
       End If
#779
.NET (C#, VB.NET, ASP) / [APORTE] PlayDir 2.0
24 Diciembre 2012, 14:14 PM
ACTUALIZADO EL 04-ENERO-2013, VERSIÓN 2.0, ALGUNOS FALLOS CORREGIDOS Y MEJORAS AÑADIDAS.

Un pequeño programa para reproducir música en el reproductor favorito.

PD: En realidad es este programa "[SOURCE] PlayLists" mejorado

     


http://www.mediafire.com/?zije2zggdmv669t


Saludos!
#780
Hola,

El problema es que estoy usando unos controles personalizados de DotNetBar (DevComponents.DotNetBar2.dll),
En la dll hay muchísimos controles, pero yo sólamente estoy usando un panel.

El tema es que la dll ocupa 5 mb, y si quiero ejecutar mi programa en otra PC pues tengo que adjuntar esa DLL.

Les pregunto si es posible reducir el tamaño de algún modo, es decir, quiero exportar sólamente el control que necesito de esa DLL sin exportar el resto de controles que hay dentro de la DLLl, para que no ocupe tanto tamaño...

Gracias.
#781
¿Que "trucos" puedo realizar para que mi APP se ejecute más rápido?

¿Podría mejorar la velocidad por ejemplo desactivando el "DoubleBuffered" del form o desactivando los estilos visuales de XP, o quizás usando una versión inferior del framework?

Conozco la existencia de NGEN, pero aparte de que no noto mejora alguna, busco otro tipo de métodos dentro de la IDE, no ejecutando software de terceros.

Un saludo!
#782
¿Como se hace?

Código (vbnet) [Seleccionar]
If Button1.Image = My.Resources.Cancel_button Then
...


operator = is not defined for types system.drawing.image and system.windows.forms.bitmap
#783
Estoy usando un extended RichTextbox que se llama "RichtextboxLinks", con ese control puedo usar el método ".InsertLink" para insertar Filelinks en el richtextbox,
y abrirlos diréctamente usando el click izquierdo dle ratón.

RichTextboxLinks > http://www.codeproject.com/Articles/9196/Links-with-arbitrary-text-in-a-RichTextBox

Lo que quiero hacer es abrir los filelinks con el click derecho en lugar de usar click izquierdo, y quiero que antes se muestre un menú contextual para seleccionar la acción a realizar,
el menú contextual contiene estos dos elementos:

1. Open file in explorer
2. Open file with...

El problema es que no tengo ni idea de como hacerlo. he intentado añadir el handle del evento junto al contextmenu pero me dice que la firma es incompatible para el handle del "InsertLink".

Este es el sub que tengo y que maneja el evento cuando un "FileLink" se clicka con el botón izquierdo dle ratón:


(e.LinkText contiene el text del FileLink)
Código (vbnet) [Seleccionar]
' This event happens when a FileLink is clicked
   Private Sub results_box_LinkClicked_1(sender As Object, e As LinkClickedEventArgs) Handles results_box.LinkClicked  ' I can't add here a handle for the contextmenu: "results_box.ContextMenu" but anyway I don't know if that is the way to do it

      NewMenu.show
       ' Dim FileInformation = My.Computer.FileSystem.GetFileInfo(e.LinkText)
       ' Process.Start("explorer.exe", " /select," & FileInformation.DirectoryName & "\" & FileInformation.Name)
   End Sub



PD: Más info aquí: http://stackoverflow.com/questions/13994639/contextmenu-in-a-richtextbox-for-open-a-filelink#comment19317914_13994639

#784


¿Porque co*#$@~ no puedo eliminar ningún control de la interface?  :-[

Realmente mi VS me odia mucho...  :-(
#785
Si creo un nuevo proyecto, este es mi Toolbox:


Pero si abro un proyecto antiguo, el toolbox cambia y se eliminan todos los controles que agregué manualmente:


¿Porque Microsoft me odia tanto?
#786
por ejemplo:
Código (vbnet) [Seleccionar]
imports System.Runtime.InteropServices
Guid("0000010c-0000-0000-c000-000000000046")


o:
Código (vbnet) [Seleccionar]
System.Runtime.InteropServices.Guid("0000010c-0000-0000-c000-000000000046")


¿Existe alguna diferencia al importar, como podría ser por ejemplo... mayor velocidad en el código u otro tipo de optimizaciones?,
¿O podemos usarlas directamente como en el segundo ejemplo sin preocupaciones?

Yo estoy acostumbrado a escribirlas directamente, me ahorran mucho tiempo por ejemplo al copiar una parte de código para añadirla en una nueva class, entonces en esa class no tengo que verificar las importaciones que son necesarias ni importar nada,
Pero no se si estoy actuando corréctamente.
#787
Es la primera vez que pruebo a hacer esto y no se que error estoy comentiendo...

Por un lado tengo la class principal (Form1)
Por otro lado tengo una class para un backgroundworker

Al usar delegados desde la segunda class para modificar la propiedad de un control de la class principal no sucede nada, la propiedad se modifica pero el control no se actualiza visualmente hablando en el form...  es decir, ni el label ni la progressbar cambian de estado :¬¬


class principal.vb :
Código (vbnet) [Seleccionar]

Public Randomize_thread As New Randomize_thread_class
...
Randomize_thread.StartBackgroundTask()
...



class del backgroundworker.vb :
Código (vbnet) [Seleccionar]


Imports PlayLists.Form1

...

   Public WithEvents Randomize_thread As New BackgroundWorker

   Public Sub InvokeControl(Of T As Control)(ByVal Control As T, ByVal Action As Action(Of T))
       If Control.InvokeRequired Then
           Control.Invoke(New Action(Of T, Action(Of T))(AddressOf InvokeControl), New Object() {Control, Action})
       Else
           Action(Control)
       End If
   End Sub

...

   Public Sub Randomize_thread_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles Randomize_thread.DoWork
       Dim lines = File.ReadAllLines(PlayLists.Form1.Temp_file)
       Dim nLines = lines.Count
       Dim randomNumbers = RandomList(nLines)
       Dim tmpFile = Path.GetTempFileName()

       InvokeControl(PlayLists.Form1.progresslabel, Sub(x) x.Visible = True)
       InvokeControl(PlayLists.Form1.ProgressBar1, Sub(x) x.Maximum += nLines)
       Using sw = New StreamWriter(tmpFile, False, Encoding.UTF8)
           For i = 0 To nLines - 1
               sw.WriteLine(lines(randomNumbers(i)))
               InvokeControl(PlayLists.Form1.ProgressBar1, Sub(x) x.Value = i)
               InvokeControl(PlayLists.Form1.progresslabel, Sub(x) x.Text = "Randomizing " + i.ToString() + " of " + (nLines - 1).ToString() + " files.")
               ' InvokeControl(PlayLists.Form1.progresslabel, Sub(x) x.Refresh())
               ' InvokeControl(PlayLists.Form1.ProgressBar1, Sub(x) x.Refresh())
           Next
       End Using
       InvokeControl(PlayLists.Form1.progresslabel, Sub(x) x.Text = "All files launched")
   End Sub
#788
¿Que diferencias hay entre compilar un control para FW2.0 y FW4.x?, es decir, modificar la versión en las propiedades del proyecto del control...
¿Si lo compilo para FW4.x será más optimizado/liviano el control en los proyectos que usen FW4.x?

¿En que FW es aconsejable compilarlo? (Porfavor dar una razón de peso que no séa "FW3.X es el más instalado en PC's standard", busco eficacia)

Gracias por leer!
#789
He buscado información sobre esto y siempre encuentro la misma respuesta , que no me sirve o no sé utilizarla XD.

1. - Tengo un richtextbox donde se agregan nombres de archivos, y quiero que al pulsar en cada nombre, se abra la carpeta (no el archivo) del archivo seleccionado, he pensado que para esto sería necesario crear un filelink, pero... no me funciona:

2. - Otro problema que tengo es que necesito desactivar los hyperlinks que se acoplan al nombre del archivo (www.newpct.com) y quizás no sé si eso me está impidiendo crear correctamente los filelink...

3. - Y otra cosa que me gustaría hacer es, un evento para que al pulsar click DERECHO sobre el filelink aparezca un contextmenu, lo del contextmenu se hacerlo, lo del evento NO xD

El código lo tengo así:

Código (vbnet) [Seleccionar]
...
AppendText(results_box, Color.White, ControlChars.Quote & "file://" & File.FullName.ToString() & ControlChars.Quote & vbNewLine)
...


Y esto es un ejemplo del primer y el segundo problema mencionados:



PD: La propiedad de detect urls la tengo activada
#790
Esto dará una excepción, porque el nombre es "el mismo" solo que con las minus/mayus cambiadas... (Vaya estúpida excepción!)
Código (vbnet) [Seleccionar]
My.Computer.FileSystem.RenameFile("C:\tEsT.txt", "test.txt")
My.Computer.FileSystem.RenameDirectory("C:\OldDirectory", "OldDIRECTORY")


Para evitarlo conozco dos técnicas,
La primera es renombrar el archivo añadiendole un caracter al final del nombre del archivo, y luego volverlo a renombrar al nombre original añadiendo el formato "ProperCase" que queramos.
La segunda (Gracias Kub0x) es mover el archivo al mismo lugar con el "ProperCase", es decir:

Archivo de origen: C:\tEST.TxT
Archivo de destino: C:\Test.txt

Quisiera saber si existe una forma que no implique tener que mover el archivo, y que no implique tener que añadirle caracteres al final del nombre original.

Saludos!
#791
¿Como puedo convertir un string a TitleCase? ya que TextInfo.ToTitleCase en realidad convierte a Word-Case  :-X

Esto No Es Lo Que Quiero
Esto si es lo que quiero

Puedo hacerlo de manera rebuscada primero obteniendo y modificando el primer caracter de la variable a UpperCase y luego anexar el resto del string... ¿Pero no hay una manera más...nativa?
#792
¿Que es un Snippet?

Es una porción de código que suele contener una o varias Subrutinas con el propósito de realizar una tarea específica,
cuyo código es reusable por otras personas y fácil de integrar con sólamente copiar y pegar el contenido del Snippet.

[youtube=960,540]https://www.youtube.com/watch?v=6E3AEs66KaQ[/youtube]




( click para ver el índice )

#793
- ¿Porque no me funciona?
- ¿Y se puede cargar un archivo xml local sin setearlo en un string?

Código (vbnet) [Seleccionar]
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO



Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim rawXML As String = _
      "<Company>" & _
      "  <Employee>" & _
      "    <name>John</name>" & _
      "    <Id>1</Id>" & _
      "    <email>John@xxxxxx.com</email>" & _
      "  </employee>" & _
      "  <employee>" & _
      "    <name>Sue</name>" & _
      "    <Id>2</Id>" & _
      "    <email>Sue@xxxxxx.com</email>" & _
      "  </employee>" & _
      "</Company>"

        Dim xmlDoc As New XmlDocument
        Dim employeeNodes As XmlNodeList
        Dim employeeNode As XmlNode
        Dim baseDataNodes As XmlNodeList
        Dim bFirstInRow As Boolean

        MsgBox("A")
        xmlDoc.LoadXml(rawXML)
        ' Este msgbox no se llega a ver
        MsgBox("B")
        employeeNodes = xmlDoc.GetElementsByTagName("name")

        For Each employeeNode In employeeNodes
            baseDataNodes = employeeNode.ChildNodes
            bFirstInRow = True

            For Each baseDataNode As XmlNode In baseDataNodes
                If (bFirstInRow) Then
                    bFirstInRow = False
                Else
                    MsgBox(", ")
                End If
                MsgBox(baseDataNode.Name & ": " & baseDataNode.InnerText)
            Next
        Next
    End Sub
End Class
#794
EDITO: Esto ya no necesito saberlo




Código (vbnet) [Seleccionar]
Module InvokeRequiredHandler
   <System.Runtime.CompilerServices.Extension()> _
   Public Sub HandleInvokeRequired(Of T As ISynchronizeInvoke)(ByVal controlToInvoke As T, ByVal actionToPerform As Action(Of T))
       'Check to see if the control's InvokeRequired property is true
       If controlToInvoke.InvokeRequired Then
           'Use Invoke() to invoke your action
           controlToInvoke.Invoke(actionToPerform, New Object() {controlToInvoke})
       Else
           'Perform the action
           actionToPerform(controlToInvoke)
       End If
   End Sub
End Module


Si por ejemplo, desde otro hilo quisiera modificar la propiedad "Text" de un textbox... ¿Como lo hago?
HandleInvokeRequired(Textbox1, ¿?)
No se que argumento se puede usar como "Action"
#795
¿Alguien me puede explicar que significan y como se usan estos tags?

Código (xml) [Seleccionar]
         <ID>aaaaaaaaa</ID>
         <ToolTip>sfsdf</ToolTip>
         <Default></Default>
         <Function>sdfsdf</Function>


Este es un snippet que he hecho (el code lo he copiado de internet), el snippet me funciona, se muestra en el menú de los snippets, pero digo yo que esos tags servirán para algo, no?

Código (xml) [Seleccionar]
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
   <Header>
     <SnippetTypes>
       <SnippetType>Expansion</SnippetType>
     </SnippetTypes>
     <Title>
        Determinar si un TextFile es Unicode
     </Title>
     <Author>Elektro H@cker</Author>
     <Description>
        Función que manda un valor boolean TRUE o FALSE
     </Description>
     <HelpUrl>
     </HelpUrl>
     <Shortcut>
     </Shortcut>
   </Header>
   <Snippet>
     <Declarations>
       <Literal Editable="true">
         <ID>aaaaaaaaa</ID>
         <ToolTip>sfsdf</ToolTip>
         <Default>
         </Default>
         <Function>sdfsdf</Function>
       </Literal>
     </Declarations>
     <Code Language="vb"><![CDATA[

   ' Dim file_codification As String = is_unicode("C:\File.txt")

   Private Function is_unicode(ByVal path As String) As Boolean
       Dim enc As System.Text.Encoding = Nothing
       Dim file As System.IO.FileStream = New System.IO.FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)
       If file.CanSeek Then
           Dim bom As Byte() = New Byte(3) {}
           file.Read(bom, 0, 4)
           If (bom(0) = &HEF AndAlso bom(1) = &HBB AndAlso bom(2) = &HBF) OrElse (bom(0) = &HFF AndAlso bom(1) = &HFE) OrElse (bom(0) = &HFE AndAlso bom(1) = &HFF) OrElse (bom(0) = 0 AndAlso bom(1) = 0 AndAlso bom(2) = &HFE AndAlso bom(3) = &HFF) Then ' ucs-4
               Return True
           Else
               Return False
           End If
           file.Seek(0, System.IO.SeekOrigin.Begin)
       Else
           Return False
       End If
   End Function

]]></Code>
   </Snippet>
 </CodeSnippet>
</CodeSnippets>

#796
Hola,
Busco controles gratis para WF y WPF que estén bien y valgan la pena usarlos (de la temática que séa, mientras séan útiles), me gustaría poder disponer de una gran cantidad para obtener mejor experiencia y programar de una manera más sencilla y fluida.

¿Que controles gratis me recomiendan?

Dispongo sólamente de estos:
CitarAlphaGradientPanel.dll
Blinkertextbox.dll
DateAndTimeControls.dll
ExtendedTextBox.dll
gGlowBox.dll
ImageControl.dll
KISControls.dll
Ookii.Dialogs.dll
Ookii.Dialogs.Wpf.dll
ProgBar.dll
SPB.dll
TransparentLabel.dll
WindowsFormsToolkit.dll
WPFAutoCompleteBox.dll

Un saludo!
#797
Hola,

¿Cuales de estos elementos trabajan en segundo plano al llamarlos, y cuales NO (osea cuales congelan la class)?




Sub
Function
Module
Una class distinta a la actual
(No se me ocurren más elementos que preguntar...)




Por ejemplo un thread , all llamarlo trabaja en segundo plano sin congelar la app, pues a eso me refiero, ¿hay otros elementos que trabajen en segundo plano?

Muchas gracias
#798
Scripting / [RUBY] [WINDOWS] Pastebin Uploader
10 Diciembre 2012, 21:02 PM


 ____        _  _
(  _ \      / )( \
 ) __/      ) \/ (
(__)astebin \____/ploader








Pastebin ha modificado la API así que el uploader de Doddy ya no funciona,
el programa "Click.to" es una muy buena alternativa si se quiere subir anónimamente a Pastebin, pero es muy limitad, así que he codeado esta versión en Ruby, para Windows.

PD: El formato del archivo se auto-reconoce (Ej. DOS), aunque aún faltan muchos formatos por añadir.


- Puedes configurar tu cuenta de Pastebin:



- Puedes subir varios archivos a la vez:



- Permite el uso del asterísco:



- Recomiendo encarecidamente usar una cuenta registrada en el script, porque el límite de uploads para "invitados" es de 10 archivos (mientras que para registrados son 25, y para premium 250):



Citar

[Modo de empleo]

 PU (Opciones opcionales) (Archivo)

[Opciones]

 -r  --raw
     Postea el código sin formato.

 -p  --private
     Marca el archivo como privado (Solo para usuarios registrados).

 -c  --config
     Establece los datos de acceso a una cuenta de Pastebin.

 /?   Muestra esta ayuda.


[Ejemplos]
 
  • PU Archivo.txt
         Devuelve el enlace directo del archivo.

     
  • PU "C:\Archivo1.txt" "C:\Archivo2.bat" "C:\Archivo3.xml"
         Devuelve el enlace directo de varios archivos.

     
  • PU --raw Archivo.vbs
         Postea el código sin formato, y devuelve el enlace directo del archivo.

     
  • PU --private "C:\Archivo.txt"
         Marca el archivo como privado, y devuelve el enlace directo del archivo.

     
  • PU --config
         Muestra el menú de configuración de cuenta de acceso.

    [/font]




PU.exe
http://www.mediafire.com/?u967oeb4pc7m71y


Pastebin Uploader.exe (Instalador para el menú contextual del mouse)
http://www.mediafire.com/download.php?a9subk9tssu499l






PU.rb

Código (ruby) [Seleccionar]
# -*- coding: UTF-8 -*-


require 'rest_client'
require 'openssl'
require 'win32/registry'


exit if Object.const_defined?(:Ocra)


$files   = ""


def logo()
 print '
 ____        _  _
(  _ \      / )( \            [v0.2] By Elektro H@cker
 ) __/      ) \/ (
(__)astebin \____/ploader

'
end


def help()
print '
[Modo de empleo]

 PU (Opciones opcionales) (Archivo)



[Opciones]

 -r  --raw
     Postea el código sin formato.

 -p  --private
     Marca el archivo como privado (Solo para usuarios registrados).

 -c  --config
     Establece los datos de acceso a una cuenta de Pastebin.

 /?   Muestra esta ayuda.



[Ejemplos]

 [+] PU Archivo.txt
     Devuelve el enlace directo del archivo.

 [+] PU "C:\Archivo1.txt" "C:\Archivo2.bat" "C:\Archivo3.xml"
     Devuelve el enlace directo de varios archivos.

 [+] PU --raw Archivo.vbs
     Postea el código sin formato, y devuelve el enlace directo del archivo.

 [+] PU --private "C:\Archivo.txt"
     Marca el archivo como privado, y devuelve el enlace directo del archivo.

 [+] PU --config
     Muestra el menú de configuración de cuenta de acceso.

'
exit
end


def arguments()

 $privacity = 0

 # empty arguments
 if (ARGV.empty?) then help() end

 ARGV.each do |arg|

 # /?
   if arg == "/?" then help() end

 # -c --config
   if arg =~ /-c\z/i or arg =~ /--config\z/i then configure() end

 # private
   if arg =~ /-p\z/i or arg =~ /--private\z/i then $privacity = 2 end

 # -r --raw
   if arg =~ /-r\z/i or arg =~ /--raw\z/i then $raw="yes" end

 # files to upload
   if arg[/\.[a-z]+$\z/i]
     if File.exist?(arg)
       $files=$files + arg + "\n"
     elsif
       print "  [+] ERROR\n\n      El archivo #{arg} no existe...\n"
     end
   end
 end # ARGV.each

end


def formats(file)
 if file[/\.arm$/i]   then $format = "arm" end
 if file[/\.asm$/i]   then $format = "asm" end
 if file[/\.asp$/i]   then $format = "asp" end
 if file[/\.au3$/i]   then $format = "autoit" end
 if file[/\.avs$/i]   then $format = "avisynth" end
 if file[/\.bat$/i]   then $format = "dos" end
 if file[/\.c$/i]     then $format = "c" end
 if file[/\.cmake$/i] then $format = "cmake" end
 if file[/\.cmd$/i]   then $format = "dos" end
 if file[/\.cpp$/i]   then $format = "cpp" end
 if file[/\.css$/i]   then $format = "css" end
 if file[/\.diff$/i]  then $format = "diff" end
 if file[/\.div$/i]   then $format = "div" end
 if file[/\.html$/i]  then $format = "html5" end
 if file[/\.ini$/i]   then $format = "ini" end
 if file[/\.iss$/i]   then $format = "inno" end
 if file[/\.lua$/i]   then $format = "lua" end
 if file[/\.mxml$/i]  then $format = "mxml" end
 if file[/\.nsis$/i]  then $format = "nsis" end
 if file[/\.php$/i]   then $format = "php" end
 if file[/\.pl$/i]    then $format = "perl" end
 if file[/\.ps$/i]    then $format = "powershell" end
 if file[/\.py$/i]    then $format = "python" end
 if file[/\.pyc$/i]   then $format = "pycon" end
 if file[/\.pyw$/i]   then $format = "python" end
 if file[/\.rb$/i]    then $format = "ruby" end
 if file[/\.rbw$/i]   then $format = "ruby" end
 if file[/\.reg$/i]   then $format = "reg" end
 if file[/\.sh$/i]    then $format = "bash" end
 if file[/\.sql$/i]   then $format = "sql" end
 if file[/\.tcl$/i]   then $format = "tcl" end
 if file[/\.txt$/i]   then $format = "text" end    
 if file[/\.vb$/i]    then $format = "vbnet" end
 if file[/\.vhdl$/i]  then $format = "vhdl" end
 if file[/\.vim$/i]   then $format = "vim" end
 if file[/\.xml$/i]   then $format = "xml" end
 if file[/\.yaml$/i]  then $format = "yaml" end
end


def configure()
 $profile = "invalid login"
   print "\n Puede configurar su cuenta de acceso de Pastebin para subir los archivos...\n\n"

   until not $profile["invalid login"]
     print " [+] Escriba su nombre de usuario: "
     $user=STDIN.gets
     if $user == "\n" then $user="guest\n" end

     print " [+] Escriba su password: "
     $pass=STDIN.gets
     if $pass == "\n" then $pass="guest\n" end

     get_userkey()
     
     if $profile["invalid login"] and not $user+$pass=="guest\nguest\n"
       print "\n [+] ERROR\n\n     El nombre de usuario o contraseña son incorrectos.\n\n"
     elsif $user=="guest\n" and $pass=="guest\n"
       $profile="guest"
     end
   end # until
   userencrypted=cifrar($user, "DES-EDE3-CBC")
   passencrypted=cifrar($pass, "DES-EDE3-CBC")
   regwrite("USER", userencrypted)
   regwrite("PASS", passencrypted)
   puts "\n Datos configurados, vuelva a ejecutar el programa..."
   exit
end


def get_userkey()
 $profile = RestClient.post('http://pastebin.com/api/api_login.php',
   :api_dev_key => "412c0f8eb27faf4feb80451ff06a2c56",
   :api_user_name => $user.gsub("\n",""),
   :api_user_password => $pass.gsub("\n",""),
   :format => "xml")
 $user_key = $profile
end


def cifrar(datos, cifrado)
 encrypt = OpenSSL::Cipher::Cipher.new(cifrado)
 encrypt.encrypt
 encrypt.update(datos) + encrypt.final      
end


def descifrar(datos, cifrado)
 decrypt = OpenSSL::Cipher::Cipher.new(cifrado)
 decrypt.decrypt
 decrypt.update(datos) + decrypt.final
end


def regwrite(keyname, value)
 Win32::Registry::HKEY_CURRENT_USER.create("SOFTWARE\\PastebinUploader\\") do |reg|
   reg[keyname, Win32::Registry::REG_SZ] = value
 end
end


def regread(keyname)
 Win32::Registry::HKEY_CURRENT_USER.open("SOFTWARE\\PastebinUploader\\") do |reg|
   reg[keyname]
 end
end


def subir(file)
 begin
   $link = RestClient.post('http://pastebin.com/api/api_post.php',
   :api_option        => "paste",
   :api_dev_key       => "412c0f8eb27faf4feb80451ff06a2c56",
   :api_user_key      => $user_key,    
   :api_user_name     => $user,
   :api_user_password => $pass,
   :api_paste_private => $privacity,
   :api_paste_code    => File.read(file),
   :api_paste_name    => file,
   :api_paste_format  => $format)
 rescue
   print ' [+] ERROR

    El error puede ser debido a uno de los siguientes motivos:

    - La página esté offline.
    - El tamaño del archivo supere los 500 KB, o 10 MB para usuarios premium.
    - Haya superado el límite de 25 uploads al día, o 250 para usuarios premium.
   '
 exit
 end # exception
end


logo()
arguments()


begin
 $user=regread("USER")
 $pass=regread("PASS")
 $user=descifrar($user, "DES-EDE3-CBC").gsub("\n","")
 $pass=descifrar($pass, "DES-EDE3-CBC").gsub("\n","")
 get_userkey()
rescue
 $user="guest"
 $pass="guest"
end
$files.each_line do |file|
 $format = "text"
 if not $raw == "yes" then formats(file) end
 subir(file.gsub("\n",""))
 puts "[+] #{file.chomp}: #{$link.to_s}"
end


__END__

#799
Necesito una ayuda para saber las extensiones de estos lenguajes conocidos:

por ejemplo:
Citarjava = Java
Extensión: .jar

gracias y un saludo.

Citar4cs = 4CS
   6502acme = 6502 ACME Cross Assembler
   6502kickass = 6502 Kick Assembler
   6502tasm = 6502 TASM/64TASS
   abap = ABAP
   actionscript = ActionScript
   actionscript3 = ActionScript 3
   ada = Ada
   algol68 = ALGOL 68
   apache = Apache Log
   applescript = AppleScript
   apt_sources = APT Sources
   asymptote = Asymptote
   autoconf = autoconf
   autohotkey = Autohotkey
   awk = Awk
   bascomavr = BASCOM AVR
   basic4gl = Basic4GL
   bibtex = BibTeX
   blitzbasic = Blitz Basic
   bnf = BNF
   boo = BOO
   bf = BrainFuck
   c_mac = C for Macs
   cil = C Intermediate Language
   csharp = C#
   cpp-qt = C++ (with QT extensions)
   c_loadrunner = C: Loadrunner
   caddcl = CAD DCL
   cadlisp = CAD Lisp
   cfdg = CFDG
   chaiscript = ChaiScript
   clojure = Clojure
   klonec = Clone C
   klonecpp = Clone C++
   cmake = CMake
   cobol = COBOL
   coffeescript = CoffeeScript
   cfm = ColdFusion
   cuesheet = Cuesheet
   d = D
   dcl = DCL
   dcpu16 = DCPU-16
   dcs = DCS
   delphi = Delphi
   oxygene = Delphi Prism (Oxygene)
   dot = DOT
   e = E
   ecmascript = ECMAScript
   eiffel = Eiffel
   email = Email
   epc = EPC
   erlang = Erlang
   fsharp = F#
   falcon = Falcon
   fo = FO Language
   f1 = Formula One
   fortran = Fortran
   freebasic = FreeBasic
   freeswitch = FreeSWITCH
   gambas = GAMBAS
   gml = Game Maker
   gdb = GDB
   genero = Genero
   genie = Genie
   gettext = GetText
   go = Go
   groovy = Groovy
   gwbasic = GwBasic
   haskell = Haskell
   haxe = Haxe
   hicest = HicEst
   hq9plus = HQ9 Plus
   html4strict = HTML
   icon = Icon
   idl = IDL
   inno = Inno Script
   intercal = INTERCAL
   io = IO
   j = J
   java = Java
   java5 = Java 5
   javascript = javascript
   jquery = jQuery
   kixtart = KiXtart
   latex = Latex
   ldif = LDIF
   lb = Liberty BASIC
   lsl2 = Linden Scripting
   lisp = Lisp
   llvm = LLVM
   locobasic = Loco Basic
   logtalk = Logtalk
   lolcode = LOL Code
   lotusformulas = Lotus Formulas
   lotusscript = Lotus Script
   lscript = LScript
   m68k = M68000 Assembler
   magiksf = MagikSF
   make = Make
   mapbasic = MapBasic
   matlab = MatLab
   mirc = mIRC
   mmix = MIX Assembler
   modula2 = Modula 2
   modula3 = Modula 3
   68000devpac = Motorola 68000 HiSoft Dev
   mpasm = MPASM
   mysql = MySQL
   nagios = Nagios
   newlisp = newLISP
   oberon2 = Oberon 2
   objeck = Objeck Programming Langua
   objc = Objective C
   ocaml-brief = OCalm Brief
   ocaml = OCaml
   octave = Octave
   pf = OpenBSD PACKET FILTER
   glsl = OpenGL Shading
   oobas = Openoffice BASIC
   oracle11 = Oracle 11
   oracle8 = Oracle 8
   oz = Oz
   parasail = ParaSail
   parigp = PARI/GP
   pascal = Pascal
   pawn = PAWN
   pcre = PCRE
   per = Per
   perl6 = Perl 6
   php-brief = PHP Brief
   pic16 = Pic 16
   pike = Pike
   pixelbender = Pixel Bender
   plsql = PL/SQL
   postgresql = PostgreSQL
   povray = POV-Ray
   powershell = Power Shell
   powerbuilder = PowerBuilder
   proftpd = ProFTPd
   progress = Progress
   prolog = Prolog
   properties = Properties
   providex = ProvideX
   purebasic = PureBasic
   pys60 = Python for S60
   q = q/kdb+
   qbasic = QBasic
   rsplus = R
   rails = Rails
   rebol = REBOL
   rexx = Rexx
   robots = Robots
   rpmspec = RPM Spec
   gnuplot = Ruby Gnuplot
   sas = SAS
   scala = Scala
   scheme = Scheme
   scilab = Scilab
   sdlbasic = SdlBasic
   smalltalk = Smalltalk
   smarty = Smarty
   spark = SPARK
   sparql = SPARQL
   stonescript = StoneScript
   systemverilog = SystemVerilog
   tsql = T-SQL
   teraterm = Tera Term
   thinbasic = thinBasic
   typoscript = TypoScript
   unicon = Unicon
   uscript = UnrealScript
   ups = UPC
   urbi = Urbi
   vala = Vala
   vbnet = VB.NET
   vedit = Vedit
   verilog = VeriLog
   visualprolog = Visual Pro Log
   visualfoxpro = VisualFoxPro
   whitespace = WhiteSpace
   whois = WHOIS
   winbatch = Winbatch
   xbasic = XBasic
   xorg_conf = Xorg Config
   xpp = XPP
   yaml = YAML
   z80 = Z80 Assembler
   zxbasic = ZXBasic
#800
Hola,

Llevo varios años buscando una solución a este problema, que es para verdaderos expertos y conocedores de las entrañas de Windows. En todos estos años no he encontrado respuesta ni solución alguna, y aquí vengo a volverlo a intentar.

Cuando creamos un archivo en el escritorio, la alineación por defecto de Windows es "de esquina superior izquierda hacia abajo", así:



Lo que yo siempre he pretendido hacer es modificar la alineación por defecto, por ejemplo si creo unos cuantos archivos en el escritorio, que la alineación por defecto séa de abajo-izquierda a derecha, así:



¿Alguien sabe si es posible? Algún valor de registro, algún recurso DLL que editar?

Sé que la versión China de Windows 7 tiene una alineación distinta, empieza desde la esquina arriba-derecha a abajo, por lo tanto esto Microsoft lo puede hacer sin problemas, lo que no sé es si un usuario puede hacerlo.

PD: Daros cuenta que no busco el típico programa que por ejemplo dibuja un "reloj" con los iconos del escritorio u otras figuras para organizar el escritorio... lo que yo quiero es cambiar la alineación por defecto.

PD2: Uso Windows 7
#801
Para los que no lo sepan, estoy diseñando un programa, y tenía un problema, la app se colgaba al darle al botón "start", hasta que "el proceso" finalizaba no podía tocar nada.
...
...
Después de estar días para conseguir meter una función en un thread separado, ahora que lo he conseguido ...no hay ninguna diferencia... hasta que no finaliza "el proceso" no puedo mover el form por la pantalla, ni pulsar cualquier botón del form, ni nada, solo puedo esperar hasta que acabe...

...Espero alguna ayuda, porqué yo ya no sé que más intentar para que no se me cuelgue, no sé lo que he hecho mal.



Hasta que no se terminan de mostrar todas las líneas del richtextbox no me deja tocar NADA.

...Muchas gracias por leer.




El form:

Código (vbnet) [Seleccionar]
Imports System.IO
Imports System.Threading
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports Ookii.Dialogs

Public Class Form1

#Region "Declarations"

   ' MediaInfo
   Dim MI As MediaInfo

   ' Others
   Dim NameOfDirectory As String = Nothing
   Dim aFile As FileInfo

#End Region

#Region "Properties"
#End Region

#Region "Load / Close"

   ' Load
   Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       ' MediaInfo Instance
       MI = New MediaInfo

   End Sub

#End Region

#Region "Get Total files Function"
#End Region

#Region "Option checkboxes"
#End Region

#Region "Folder buttons"
#End Region


#Region "Append text function"

   ' Append Text
   Public Sub AppendText(box As RichTextBox, color As Color, text As String)

       Control.CheckForIllegalCrossThreadCalls = False

       Dim start As Integer = box.TextLength
       box.AppendText(text)
       Dim [end] As Integer = box.TextLength

       ' Textbox may transform chars, so (end-start) != text.Length
       box.[Select](start, [end] - start)
       If True Then
           box.SelectionColor = color
           ' could set box.SelectionBackColor, box.SelectionFont too.
       End If
       box.SelectionLength = 0
       ' clear
   End Sub

#End Region


#Region "Thread"

   Public _WaitHandle_FirstThreadDone As New System.Threading.AutoResetEvent(False)

   Public Sub ThreadProc(ByVal aDir As DirectoryInfo)

       Dim aFile As FileInfo

       For Each aFile In aDir.GetFiles()

           If accepted_extensions.ToLower.Contains(aFile.Extension.ToLower) Then

               ' print output
               AppendText(consolebox, Color.Yellow, "Processing: ")
               AppendText(consolebox, Color.White, aFile.ToString() + vbNewLine)
               consolebox.ScrollToCaret()
               processedfiles += 1
               totalfiles_label.Text = "Processed " + processedfiles.ToString() + " of " + totalfiles.ToString() + " total video files"

               ' Attributes
               If attribs = True Then
                   aFile.Attributes = (aFile.Attributes And Not FileAttributes.ReadOnly And Not FileAttributes.Hidden And Not FileAttributes.System And Not FileAttributes.Archive)
               End If

               ' Rename to Word-Case
               If wordcase = True Then
                   Dim renamestr As String = StrConv(aFile.Name, VbStrConv.ProperCase)
                   My.Computer.FileSystem.RenameFile(aFile.FullName, renamestr + "_FILMEN")
                   My.Computer.FileSystem.RenameFile(aFile.FullName + "_FILMEN", renamestr)
               End If

               ' Rename to Lower-Case
               If lowercase = True Then
                   Dim renamestr As String = StrConv(aFile.Name, VbStrConv.Lowercase)
                   My.Computer.FileSystem.RenameFile(aFile.FullName, renamestr + "_FILMEN")
                   My.Computer.FileSystem.RenameFile(aFile.FullName + "_FILMEN", renamestr)
               End If

               ' Playlists
               If playlist = True Then
                   Using writer As StreamWriter = New StreamWriter(aFile.DirectoryName.ToString() & "\" & aDir.Name & ".m3u", True, System.Text.Encoding.UTF8)
                       writer.WriteLine(aFile.FullName.ToString())
                   End Using
               End If

               ' MEDIAINFO:  (ac3, dts, wav and multitrack)
               If ac3 = True Or dts = True Or wav = True Or multitrack = True Then

                   MI.Open(aFile.FullName)

                   Dim Pos As Integer = 0
                   To_Display = Nothing

                   ' multitrack
                   If multitrack = True Then
                       If MI.Count_Get(StreamKind.Audio) > 1 Then
                           results_box.AppendText("Multi Track: " + aFile.FullName.ToString() + vbNewLine)
                           results_box.SelectionStart = results_box.Text.Length
                           results_box.ScrollToCaret()
                           problems += 1
                           problems_label.Text = problems.ToString() + " problems found"
                       End If
                   End If

                   While Pos < MI.Count_Get(StreamKind.Audio)

                       ' AC-3
                       If ac3 = True Then
                           If MI.Get_(StreamKind.Audio, Pos, "Format").ToString() = "AC-3" Then
                               results_box.AppendText("AC3 Track: " + aFile.FullName.ToString() + vbNewLine)
                               results_box.SelectionStart = results_box.Text.Length
                               results_box.ScrollToCaret()
                               problems += 1
                               problems_label.Text = problems.ToString() + " problems found"
                           End If
                       End If

                       ' DTS
                       If dts = True Then
                           If MI.Get_(StreamKind.Audio, Pos, "Format").Contains("DTS") Then
                               results_box.AppendText("DTS Track: " + aFile.FullName.ToString() + vbNewLine)
                               results_box.SelectionStart = results_box.Text.Length
                               results_box.ScrollToCaret()
                               problems += 1
                               problems_label.Text = problems.ToString() + " problems found"
                           End If
                       End If

                       ' WAV
                       If wav = True Then
                           If MI.Get_(StreamKind.Audio, Pos, "Format").Contains("PCM") Then
                               results_box.AppendText("WAV Track: " + aFile.FullName.ToString() + vbNewLine)
                               results_box.SelectionStart = results_box.Text.Length
                               results_box.ScrollToCaret()
                               problems += 1
                               problems_label.Text = problems.ToString() + " problems found"
                           End If
                       End If

                       System.Math.Max(System.Threading.Interlocked.Increment(Pos), Pos - 1)
                   End While
               End If

               If metadata = True Then
                   Dim ffmpeg_process As New Process()
                   Dim ffmpeg_startinfo As New ProcessStartInfo()
                   ffmpeg_startinfo.FileName = "cmd.exe "
                   ffmpeg_startinfo.Arguments = "/C ffmpeg.exe -y -i " & ControlChars.Quote & aFile.FullName.ToString() & ControlChars.Quote & " -f ffmetadata " & ControlChars.Quote & "%TEMP%\" & aFile.Name.ToString() & "_metadata.txt" & ControlChars.Quote & " >NUL 2>&1 && Type " & ControlChars.Quote & "%TEMP%\" & aFile.Name.ToString() & "_metadata.txt" & ControlChars.Quote & "| FINDSTR /I " & ControlChars.Quote & "^INAM ^title" & ControlChars.Quote & " >NUL && Echo FOUND && EXIT || Echo NOT FOUND && Exit"
                   ffmpeg_startinfo.UseShellExecute = False
                   ffmpeg_startinfo.CreateNoWindow = True
                   ffmpeg_startinfo.RedirectStandardOutput = True
                   ffmpeg_startinfo.RedirectStandardError = True
                   ffmpeg_process.EnableRaisingEvents = True
                   ffmpeg_process.StartInfo = ffmpeg_startinfo
                   ffmpeg_process.Start()
                   ffmpeg_process.WaitForExit()

                   Dim readerStdOut As IO.StreamReader = ffmpeg_process.StandardOutput
                   Dim FINDstdOut As String = ffmpeg_process.StandardOutput.ReadToEnd

                   If FINDstdOut.Contains("FOUND") Then
                       AppendText(consolebox, Color.Red, "TAGS FOUND! Removing tags, please wait..." & vbNewLine)
                       Dim relative_dir As String = aDir.FullName.ToString().Replace(aDir.Root.ToString(), "\")
                       Dim ffmpegconvert_process As New Process()
                       Dim ffmpegconvert_startinfo As New ProcessStartInfo()
                       ffmpegconvert_startinfo.FileName = "cmd.exe "
                       ffmpegconvert_startinfo.Arguments = "/C MKDIR " & ControlChars.Quote & userSelectedFolderPathmetadata & relative_dir & ControlChars.Quote & " 2>NUL & ffmpeg.exe -y -i " & ControlChars.Quote & aFile.FullName.ToString() & ControlChars.Quote & " -c copy -map_metadata -1 " & ControlChars.Quote & userSelectedFolderPathmetadata & relative_dir & "\" & aFile.Name.ToString() & ControlChars.Quote & " >NUL 2>&1 & Exit"
                       ffmpegconvert_startinfo.UseShellExecute = False
                       ffmpegconvert_startinfo.CreateNoWindow = True
                       ffmpegconvert_startinfo.RedirectStandardOutput = True
                       ffmpegconvert_startinfo.RedirectStandardError = True
                       ffmpegconvert_process.EnableRaisingEvents = True
                       ffmpegconvert_process.StartInfo = ffmpegconvert_startinfo
                       ffmpegconvert_process.Start()
                       ffmpegconvert_process.WaitForExit()
                       'Dim ffmpegconvertreaderStdOut As IO.StreamReader = ffmpegconvert_process.StandardOutput
                   End If

                   Do While readerStdOut.EndOfStream = False
                       consolebox.AppendText(readerStdOut.ReadLine() + vbNewLine)
                       consolebox.SelectionStart = consolebox.Text.Length
                       consolebox.ScrollToCaret()
                   Loop

               End If
           End If
       Next

       _WaitHandle_FirstThreadDone.Set()
   End Sub


#End Region


#Region "Organize function"

   Public Sub MediaInfo(Directory)
       Dim MyDirectory As DirectoryInfo
       MyDirectory = New DirectoryInfo(NameOfDirectory)
       MediaInfoWorkWithDirectory(MyDirectory)
   End Sub

   Public Sub MediaInfoWorkWithDirectory(ByVal aDir As DirectoryInfo)
       Dim nextDir As DirectoryInfo
       Dim t As New Threading.Thread(AddressOf ThreadProc)
       t.Start(aDir)
       _WaitHandle_FirstThreadDone.WaitOne()
       For Each nextDir In aDir.GetDirectories
           If playlist = True Then
               Using writer As StreamWriter = New StreamWriter(aDir.FullName & "\" & nextDir.Name & "\" & nextDir.Name & ".m3u", False, System.Text.Encoding.UTF8)
                   'overwrite existing playlist
               End Using
           End If
           MediaInfoWorkWithDirectory(nextDir)
       Next
   End Sub

#End Region


#Region "Action buttons"

   ' start button
   Public Sub Button2_Click(sender As Object, e As EventArgs) Handles start_button.Click

       If metadata = True And metadatatextbox.Text = "Select a folder to save the converted videos without metadata..." Then
           MsgBox("You must select a folder for the saved metadata videos...", , "Filmen v1.0")
       Else
           If ac3 = False And dts = False And wav = False And multitrack = False And playlist = False And attribs = False And wordcase = False And metadata = False And lowercase = False Then
               MsgBox("You must select at least one option...", , "Filmen v1.0")
           Else

               consolebox.Clear()

               ' pause / cancel button ON
               pause_button.Enabled = True
               cancel_button.Enabled = True

               ' Total files label
               processedfiles = 0
               totalfiles_label.Text = totalfiles.ToString() + " Total video files"

               ' Problems label
               problems = 0
               problems_label.Text = "0 problems found"

               ' Organization process
               NameOfDirectory = userSelectedFolderPath
               MediaInfo(NameOfDirectory)
               consolebox.AppendText(vbNewLine + "[+] Organization finalized!" + vbNewLine)
               consolebox.Refresh()
               consolebox.SelectionStart = consolebox.Text.Length
               consolebox.ScrollToCaret()

               ' pause / cancel button OFF
               pause_button.Enabled = False
               cancel_button.Enabled = False

           End If
       End If
   End Sub

#End Region

End Class
#802
.NET (C#, VB.NET, ASP) / [SOURCE] PlayLists
29 Noviembre 2012, 18:47 PM
Bueno,
es una caca de programa porqué es el segundo programa que he hecho, y no he conseguido dejar bien la transparencia del programa ni meter la barra de progreso en un thread, pero está decente para usarse y cumple las condiciones necesarias, y me quedo satisfecho al ver la diferencia entre Batch y Winform XD

El programa sirve para seleccionar una o varias carpetas y añadirlas a la lista de reproducción del reproductor multimedia, ni más, ni menos. (Buena tool para bindearla a un "hot-corner" de la pantalla del PC)

     


Source: http://exoshare.com/download.php?uid=EJJTGEXN






Aquí dejo el "boceto" en Batch por si le sirve a alguien:

Código (dos) [Seleccionar]
@echo off
Title Winamp Auto Playlist Menu v0.1

:: Auto-redimensionado
color 07
Nircmd win center ititle "Winamp Auto Playlist Menu" >NUL 2>&1
PUSHD "%~dp0"
Set /a Lines=5
Mode con cols=50 lines=%LINES%
For /D %%# in (*) Do (Call Set /A "Lines+=2" & call Mode con cols=60 lines=%%LINES%%)

:Menu
CLS
SET "SELECT=" & SET "NUM="
For /D %%# in (*) Do (Call Set /A "Num+=1" & Call Set "Folder%%NUM%%=%%#" & Call Set "List=%%LIST%% ;%%NUM%%" & Call Echo [%%Num%%] %%# | MORE)
Echo [0] * REPRODUCIR TODO * | MORE
Echo: Seleccione una carpeta para reproducirla...
Set /P select=^>^>
Echo "%SELECT%" | FINDSTR /I "[A-Z]" >NUL && (Goto :Menu) || (Echo "%List%" | FIND ";%SELECT% " >NUL || (Goto :Menu))
If "%SELECT%" equ "0" (Goto :todo)

:Play
CLS
Call Echo Carpeta seleccionada: "%%Folder%SELECT%%%" | MORE
Call Echo: [+] Iniciando Winamp...
Call Start /B /D "%ProgramFiles(x86)%\Winamp\" winamp.exe "%CD%\%%Folder%SELECT%%%"
Timeout /T 5 & Exit

:TODO
CLS
Call Echo Carpeta seleccionada: * TODAS * | MORE
Call Echo: [+] Iniciando Winamp...
For /D %%# in (*) Do (Call Set "ARG=%%arg%% ^"%CD%\%%#^"")
Call Start /B /D "%ProgramFiles(x86)%\Winamp\" winamp.exe %%arg%%
Timeout /T 10 & Exit
#803
EDITO: Lo he resuelto creando nuevas instancias del thread dentro del loop

Tengo este thread:

Código (vbnet) [Seleccionar]
Public Sub ThreadProc(ByVal aDir As DirectoryInfo)
   Dim i As Integer
   For i = 1 To 3
       MsgBox(i)
       Thread.Sleep(500)
   Next
   _WaitHandle_FirstThreadDone.Set()
End Sub


Y tengo un búcle que hace esto:

Código (vbnet) [Seleccionar]
  loop...
   t.Start(aDir)
   _WaitHandle_FirstThreadDone.WaitOne()
  next...


El problema es que solo se ejecuta el thread una sola vez, cuando intenta iniciarse la siguiente vez me dice el debugger: "Subproceso en ejecución o terminado, no se pudo reiniciar",
y no lo entiendo, creo que le estoy indicando al thread que se "setee" como finalizado, y el loop espera a que finalize el thread.. así que no sé donde estará el problema, de verdad no lo entiendo!
#804
Estoy harto del tema de las transparencias en los winforms...

aver si me podeis ayudar, el problema es sencillo, la solución...no lo sé.

un label "transparente" encima de una barra de progreso:


¿Como puedo hacerlo transparente de verdad?

Gracias...
#805
Pues eso, ¿Sería posible cambiar el color de UNA sola línea de este richtextbox para que la línea de "Processing: ..." saliera en amarillo por ejemplo?

Y otra pregunta relacionada, ¿Sería posible cambiar solamente UNA palabra de color?

Agradezco cualquier información!

#806
Hola,

Necesito agarrar el error output de la CMD en este código, pero no sé como hacerlo, solo me agarra el output standard. ¿Me pueden indicar como se hace?

Muchas gracias!

PD: Ya sé que es una mala práctica usar comandos externos, pero no encuentro ninguna librería que sirva para buscar metadataos Y A LA VEZ convertir videos, eso es dificil, estoy aprendiendo!


Código (VBNET) [Seleccionar]
               If metadata = True Then
                   Dim ffmpeg_process As New Process()
                   Dim ffmpeg_startinfo As New ProcessStartInfo()
                   ffmpeg_startinfo.FileName = "cmd.exe "
                   ffmpeg_startinfo.UseShellExecute = False
                   ffmpeg_startinfo.CreateNoWindow = False
                   ffmpeg_startinfo.Arguments = "/C ffmpeg.exe -y -i " & ControlChars.Quote & aFile.FullName.ToString() & ControlChars.Quote & " -f ffmetadata " & ControlChars.Quote & "%TEMP%\" & aFile.Name.ToString() & "_metadata.txt" & ControlChars.Quote & " >NUL 2>&1 && Type " & ControlChars.Quote & "%TEMP%\" & aFile.Name.ToString() & "_metadata.txt" & ControlChars.Quote & "| FINDSTR /I " & ControlChars.Quote & "^INAM ^title" & ControlChars.Quote
                   ffmpeg_startinfo.RedirectStandardOutput = True
                   ffmpeg_process.EnableRaisingEvents = True
                   ffmpeg_process.StartInfo = ffmpeg_startinfo
                   ffmpeg_process.Start()
                   Dim readerStdOut As IO.StreamReader = ffmpeg_process.StandardOutput
                   Do While readerStdOut.EndOfStream = False
                       consolebox.AppendText(readerStdOut.ReadLine() + vbNewLine)
                       consolebox.SelectionStart = consolebox.Text.Length
                       consolebox.ScrollToCaret()
                   Loop
               End If
#807
Hola,

A ver, tengo un richtextbox que "printa" información hasta finalizar el búcle FOR

Lo que pasa es que mi form se cuelga, no puedo tocar NADA,
Lo que necesito es poder detener (detener del todo) el proceso o mantenerlo en espera (Pause) mediante un botón, o un evento de teclado, o las dos cosas!, pero preferiblemente un botón que esté destinado a pausar el proceso, y otro botón destinado a detener el proceso por completo.

¿Alguien me puede indicar como hacerlo porfavor? No lo quiero hecho, quiero aprender a hacerlo pero no se por donde buscar!

Muchas gracias.



Código (vbnet) [Seleccionar]
   Public Sub MediaInfoWorkWithFilesInDir(ByVal aDir As DirectoryInfo)

       Dim aFile As FileInfo
       For Each aFile In aDir.GetFiles()
           If accepted_extensions.ToLower.Contains(aFile.Extension.ToLower) Then

               MI.Open(aFile.FullName)

               Dim Pos As Integer = 0
               To_Display = Nothing
               While Pos < MI.Count_Get(StreamKind.Audio)
                   To_Display += "| " + MI.Get_(StreamKind.Audio, Pos, "Format")
                   System.Math.Max(System.Threading.Interlocked.Increment(Pos), Pos - 1)
               End While

               consolebox.AppendText("Processing: " + aFile.ToString() + To_Display.ToString() + vbNewLine)
               consolebox.SelectionStart = consolebox.Text.Length
               consolebox.ScrollToCaret()

           End If
       Next
   End Sub
#808
Hola,

Mi app trabaja sobre MILES de archivos y quisiera saber si puedo mejorar este for para disminuir el tiempo de procesado:

Código (vbnet) [Seleccionar]

Dim accepted_extensions As String = ".264 .3gp .asf .asx .avi .avc .bsf .bdmv .divx .dv .evo .f4v .flv .hdmov .m1v .m2t .m2ts .m2v .m4v .mkv .mov .mp4 .mpeg .mpg .mpv4 .mts .ogm .ogv .qt .rmvb .swf .ts .vob .webm .wmv"

   Public Sub PlaylistsWorkWithFilesInDir(ByVal aDir As DirectoryInfo)
       consolebox.AppendText("Processing: " + aDir.ToString() + vbNewLine)
       consolebox.SelectionStart = consolebox.Text.Length
       consolebox.ScrollToCaret()
       Dim aFile As FileInfo
       For Each aFile In aDir.GetFiles()
           If accepted_extensions.ToLower.Contains(aFile.Extension.ToLower) Then
               Using writer As StreamWriter = New StreamWriter(aFile.DirectoryName.ToString() & "\" & aDir.Name & ".m3u", True, System.Text.Encoding.UTF8)
                   writer.WriteLine(aFile.FullName.ToString())
               End Using
           End If
       Next
   End Sub


Me pregunto si existirá algún método en el sistema para comprobar si el archivo es un archivo de video, algo así:
If IO.FileType(aFile) = "VideoFile" Then...
#809
Hola,

Tengo una pregunta antes de la verdadera pregunta xD

¿Que control es el más adecuado para mostrar el output de la CMD?  (Estoy usando un richtextbox)

Y bueno, el problema es que no consigo que el texto cambie antes d emostrar el output:
Código (vbnet) [Seleccionar]
Me.consolebox.Text = "Deleting the attributes of the files..."

Todo lo demás funciona bien, pero no consigo mostrar ese string, se queda el richtextbox vacío hasta que finaliza el búcle...

Código (vbnet) [Seleccionar]
  Private Function attrib() As Boolean
       Me.consolebox.Text = "Deleting the attributes of the files..."
       Dim attrib_process As New Process()
       Dim attrib_startinfo As New ProcessStartInfo()
       Dim attrib_args As String = videofolder
       attrib_startinfo.FileName = "cmd.exe "
       attrib_startinfo.UseShellExecute = False
       attrib_startinfo.CreateNoWindow = True
       attrib_startinfo.Arguments = "/C PUSHD " & ControlChars.Quote & videofolder & ControlChars.Quote & " & Attrib -A -R -S -H -I /S *.* & attrib +H /S *.ico >nul & attrib +H -R /S *.ini >nul"
       attrib_startinfo.RedirectStandardOutput = True
       attrib_process.EnableRaisingEvents = True
       attrib_process.StartInfo = attrib_startinfo
       attrib_process.Start()
       Dim readerStdOut As IO.StreamReader = attrib_process.StandardOutput
       Do While readerStdOut.EndOfStream = False
           output = output + readerStdOut.ReadLine()
       Loop
       Me.consolebox.Text = "This is the result of the command:" + output
   End Function


¿Y si necesito usar un comando de múltiples líneas como le hago?

por ejemplo:
Código (vbnet) [Seleccionar]
attrib_startinfo.Arguments = "/C
Echo linea 1 &
(Echo linea2
Echo linea 3)
"
#810
MOD: Perdón, tuve un error, juraría que posteé esto en dudas generales, si me lo pudieran mover allá...





Hola,

Como navegador uso Firefox

Y actualmente yo no uso seamonkey, uso una extensión que se llama "customizeyourweb" https://addons.mozilla.org/en-us/firefox/addon/customize-your-web/

Me gustaría saber si en este tipo de extensiones parecidas al seamonkey hay alguna forma de desmarcar una casilla en una página web que siempre aparece la casilla marcada.

Gracias.