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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Windows Form transparente
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Windows Form transparente  (Leído 3,967 veces)
diegoCmC

Desconectado Desconectado

Mensajes: 177



Ver Perfil
Windows Form transparente
« en: 30 Marzo 2014, 22:59 pm »

Hola a todos. Ando creando una aplicacion en c#, y quiero mostrar una ventana desde mi aplicacion (como se haria con un messagebox).

El problema esta en que en lugar de una ventana con texto lo que quiero invocar es un grupo de textbox, pero sin que se encuentren dentro de una ventana con bordes, solo los textbox.

La unica solucion que he encontrado es crear un form, definir los bordes y el fondo transparentes, y poner dentro los textbox, pero mi pregunta es si no existe ninguna clase en System.windows.forms en la que se permita mostrar solo controles, sin falta de encontrarse en ventanas.

Espero que la pregunta quede mas o menos clara, que no es nada facil de explicar :huh:

gracias de antemano.


En línea

a todas las que me abrieron su coraza traeles suerte
ya no creo en el amor pero querria volver a verte
El Benjo


Desconectado Desconectado

Mensajes: 392



Ver Perfil WWW
Re: Windows Form transparente
« Respuesta #1 en: 31 Marzo 2014, 01:11 am »

Puedes hacerlo poniendo la propiedad "Transparencykey" al mismo valor que la propiedad "background".


En línea

www.es.neftis-ai.com

Sí hay un mejor lenguaje de programación y es ese con el que puedes desarrollar tus objetivos.
diegoCmC

Desconectado Desconectado

Mensajes: 177



Ver Perfil
Re: Windows Form transparente
« Respuesta #2 en: 31 Marzo 2014, 07:36 am »

Si, pero me gustaria saber si hay alguna clase derivada o algo, que ya traiga eso implementado por defecto, sin falta de que yo tenga que editar las propiedades
En línea

a todas las que me abrieron su coraza traeles suerte
ya no creo en el amor pero querria volver a verte
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Windows Form transparente
« Respuesta #3 en: 31 Marzo 2014, 09:19 am »

1. ¿Que tipo de proyecto es?.





Un control debe añadirse a un container que pueda albergar controles, por ende no se puede hacer sin una "ventana", Control.ControlCollection Class, al menos, hasta donde yo se.

Puedes heredar la Class ToolStripControlHost, para mostrar un popup con un control, pero es limitada y tiene sus inconvenientes, no te servirá de mucho.

O puedes heredar un Form, añadirle los controles y hacer el form "transparente".





Te he escrito un ejemplo completo, para un proyecto de tipo WindowsForms, pero no te acostumbres.
PD: Lo escribí en VB.NET, te servirá para orientarte y puedes traducir el código usando cualquier conversor online: http://converter.telerik.com/

Por un lado, la Class que hereda un System.Windows.Form, la cual se puede mejorar, pero es solo un ejemplo (nótese el color Fuchsia, quizas quieras cambiarlo):

EDITO: Funcionalidad extendida para mover los controles al mantener el botón del ratón.
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 03-31-2014
  4. ' ***********************************************************************
  5. ' <copyright file="ControlsForm.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' *************************************************************************
  9.  
  10. ''' <summary>
  11. ''' Class ControlsForm.
  12. ''' Invisible Form designed to host Controls.
  13. ''' </summary>
  14. Public Class ControlsForm : Inherits Form
  15.  
  16. #Region " Variables & Properties "
  17.  
  18.    ''' <summary>
  19.    ''' Indicates whether the Form and it's controls are moveable.
  20.    ''' </summary>
  21.    Private _Moveable As Boolean = False
  22.  
  23.    ''' <summary>
  24.    ''' Indicates whether the moveable events are handled
  25.    ''' </summary>
  26.    Private MoveableIsHandled As Boolean = False
  27.  
  28.    ''' <summary>
  29.    ''' Boolean Flag that indicates whether the Form should be moved.
  30.    ''' </summary>
  31.    Private MoveFormFlag As Boolean = False
  32.  
  33.    ''' <summary>
  34.    ''' Indicates the position where to move the form.
  35.    ''' </summary>
  36.    Private MoveFormPosition As Point = Nothing
  37.  
  38.    ''' <summary>
  39.    ''' Gets or sets a value indicating whether this <see cref="ControlsForm"/> and it's controls are movable.
  40.    ''' </summary>
  41.    ''' <value><c>true</c> if controls are movable; otherwise, <c>false</c>.</value>
  42.    Public Property Moveable As Boolean
  43.  
  44.        Get
  45.            Return Me._Moveable
  46.        End Get
  47.  
  48.        Set(ByVal value As Boolean)
  49.  
  50.            Me._Moveable = value
  51.  
  52.            Dim Pan As Panel =
  53.              (From p As Panel In MyBase.Controls.OfType(Of Panel)()
  54.               Where p.Tag = Me.Handle).First
  55.  
  56.            Select Case value
  57.  
  58.                Case True ' Add Moveable Events to EventHandler.
  59.  
  60.                    If Not Me.MoveableIsHandled Then ' If not Moveable handlers are already handled then...
  61.                        For Each c As Control In Pan.Controls
  62.                            AddHandler c.MouseDown, AddressOf MouseDown
  63.                            AddHandler c.MouseUp, AddressOf MouseUp
  64.                            AddHandler c.MouseMove, AddressOf MouseMove
  65.                        Next c
  66.                        Me.MoveableIsHandled = True
  67.                    End If
  68.  
  69.                Case False ' Remove Moveable Events from EventHandler.
  70.  
  71.                    If Me.MoveableIsHandled Then ' If Moveable handlers are already handled then...
  72.                        For Each c As Control In Pan.Controls
  73.                            RemoveHandler c.MouseDown, AddressOf MouseDown
  74.                            RemoveHandler c.MouseUp, AddressOf MouseUp
  75.                            RemoveHandler c.MouseMove, AddressOf MouseMove
  76.                        Next c
  77.                        Me.MoveableIsHandled = False
  78.                    End If
  79.  
  80.            End Select
  81.  
  82.        End Set
  83.  
  84.    End Property
  85.  
  86. #End Region
  87.  
  88. #Region " Constructors "
  89.  
  90.    ''' <summary>
  91.    ''' Prevents a default instance of the <see cref="ControlsForm"/> class from being created.
  92.    ''' </summary>
  93.    Private Sub New()
  94.    End Sub
  95.  
  96.    ''' <summary>
  97.    ''' Initializes a new instance of the <see cref="ControlsForm" /> class.
  98.    ''' Constructor Overload to display a collection of controls.
  99.    ''' </summary>
  100.    ''' <param name="Controls">The control array to display in the Formulary.</param>
  101.    ''' <param name="FormLocation">The default Formulary location.</param>
  102.    Public Sub New(ByVal [Controls] As Control(),
  103.                   Optional ByVal FormLocation As Point = Nothing)
  104.  
  105.        ' InitializeComponent call.
  106.        MyBase.SuspendLayout()
  107.        MyBase.Name = "ControlsForm"
  108.  
  109.        ' Adjust Form size.
  110.        MyBase.ClientSize = New Size(0, 0)
  111.        MyBase.AutoSize = True
  112.        MyBase.AutoSizeMode = AutoSizeMode.GrowAndShrink
  113.  
  114.        ' Set the Transparency properties.
  115.        MyBase.AllowTransparency = True
  116.        MyBase.BackColor = Color.Fuchsia
  117.        MyBase.TransparencyKey = Color.Fuchsia
  118.        MyBase.DoubleBuffered = False
  119.  
  120.        ' Is not necessary to display borders, icon, and taskbar, hide them.
  121.        MyBase.FormBorderStyle = BorderStyle.None
  122.        MyBase.ShowIcon = False
  123.        MyBase.ShowInTaskbar = False
  124.  
  125.        ' Instance a Panel to add our controls.
  126.        Dim Pan As New Panel
  127.  
  128.        With Pan
  129.  
  130.            ' Suspend the Panel layout.
  131.            Pan.SuspendLayout()
  132.  
  133.            ' Set the Panel properties.
  134.            .Name = "ControlsForm Panel"
  135.            .Tag = Me.Handle
  136.            .AutoSize = True
  137.            .AutoSizeMode = AutoSizeMode.GrowAndShrink
  138.            .BorderStyle = BorderStyle.None
  139.            .Dock = DockStyle.Fill
  140.  
  141.        End With
  142.  
  143.        ' Add our controls inside the Panel.
  144.        Pan.Controls.AddRange(Controls)
  145.  
  146.        ' Add the Panel inside the Form.
  147.        MyBase.Controls.Add(Pan)
  148.  
  149.        ' If custom Form location is set then...
  150.        If Not FormLocation.Equals(Nothing) Then
  151.  
  152.            ' Set the StartPosition to manual relocation.
  153.            MyBase.StartPosition = FormStartPosition.Manual
  154.  
  155.            ' Relocate the form.
  156.            MyBase.Location = FormLocation
  157.  
  158.        End If
  159.  
  160.        ' Resume layouts.
  161.        Pan.ResumeLayout(False)
  162.        MyBase.ResumeLayout(False)
  163.  
  164.    End Sub
  165.  
  166.    ''' <summary>
  167.    ''' Initializes a new instance of the <see cref="ControlsForm" /> class.
  168.    ''' Constructor Overload to display a single control.
  169.    ''' </summary>
  170.    ''' <param name="Control">The control to display in the Formulary.</param>
  171.    ''' <param name="FormLocation">The default Formulary location.</param>
  172.    Public Sub New(ByVal [Control] As Control,
  173.                   Optional ByVal FormLocation As Point = Nothing)
  174.  
  175.        Me.New({[Control]}, FormLocation)
  176.  
  177.    End Sub
  178.  
  179. #End Region
  180.  
  181. #Region " Event Handlers "
  182.  
  183.    ''' <summary>
  184.    ''' Handles the MouseDown event of the Form and it's controls.
  185.    ''' </summary>
  186.    ''' <param name="sender">The source of the event.</param>
  187.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  188.    Private Shadows Sub MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
  189.    Handles MyBase.MouseDown
  190.  
  191.        If e.Button = MouseButtons.Left Then
  192.            Me.MoveFormFlag = True
  193.            Me.Cursor = Cursors.NoMove2D
  194.            Me.MoveFormPosition = e.Location
  195.        End If
  196.  
  197.    End Sub
  198.  
  199.    ''' <summary>
  200.    ''' Handles the MouseMove event of the Form and it's controls.
  201.    ''' </summary>
  202.    ''' <param name="sender">The source of the event.</param>
  203.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  204.    Private Shadows Sub MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) _
  205.    Handles MyBase.MouseMove
  206.  
  207.        If Me.MoveFormFlag Then
  208.            Me.Location += (e.Location - Me.MoveFormPosition)
  209.        End If
  210.  
  211.    End Sub
  212.  
  213.    ''' <summary>
  214.    ''' Handles the MouseUp event of the Form and it's controls.
  215.    ''' </summary>
  216.    ''' <param name="sender">The source of the event.</param>
  217.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  218.    Private Shadows Sub MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) _
  219.    Handles MyBase.MouseUp
  220.  
  221.        If e.Button = MouseButtons.Left Then
  222.            Me.MoveFormFlag = False
  223.            Me.Cursor = Cursors.Default
  224.        End If
  225.  
  226.    End Sub
  227.  
  228. #End Region
  229.  
  230. End Class

Por otro lado, la Class de ejemplo de uso:

EDITO: Class actualizada.
Código
  1. Public Class Form1
  2.  
  3. #Region " Objects "
  4.  
  5.    ' Our inherited Form.
  6.    Protected WithEvents frm As ControlsForm = Nothing
  7.  
  8.    ' Our controls.
  9.    Friend WithEvents tb1 As New TextBox With {.Text = "Elektro-Test 1"}
  10.    Friend WithEvents tb2 As New TextBox With {.Text = "Elektro-Test 2"}
  11.    Friend WithEvents cb1 As New CheckBox With {.Text = "Elektro-Test 3", .FlatStyle = FlatStyle.Flat}
  12.  
  13. #End Region
  14.  
  15. #Region " Constructor "
  16.  
  17.    ''' <summary>
  18.    ''' Initializes a new instance of the <see cref="Form1"/> class.
  19.    ''' </summary>
  20.    Public Sub New()
  21.  
  22.        ' This call is required by the designer.
  23.        InitializeComponent()
  24.  
  25.        ' Center this form into the screen.
  26.        Me.StartPosition = FormStartPosition.CenterScreen
  27.  
  28.    End Sub
  29.  
  30. #End Region
  31.  
  32. #Region " Main Button Event Handlers "
  33.  
  34.    ''' <summary>
  35.    ''' Handles the Click event of the ButtonMain control.
  36.    ''' </summary>
  37.    Private Sub ButtonMain_Click(ByVal sender As Object, ByVal e As EventArgs) _
  38.    Handles ButtonMain.Click
  39.  
  40.        ' Set the Control locations.
  41.        tb1.Location = New Point(5, 5)
  42.        tb2.Location = New Point(tb1.Location.X, tb1.Location.Y + CInt(tb1.Height * 1.5R))
  43.        cb1.Location = New Point(tb2.Location.X, tb2.Location.Y + CInt(tb2.Height * 1.5R))
  44.  
  45.        ' Instance the Form that will store our controls.
  46.        If frm Is Nothing Then
  47.            frm = New ControlsForm({tb1, tb2, cb1},
  48.                       New Point(Me.Bounds.Right, Me.Bounds.Top))
  49.        End If
  50.  
  51.        With frm
  52.            .Moveable = True ' Set the Controls moveable.
  53.            .Show() ' Display the invisible Form.
  54.        End With
  55.  
  56.    End Sub
  57.  
  58. #End Region
  59.  
  60. #Region " Textbox's Event Handlers "
  61.  
  62.    ''' <summary>
  63.    ''' Handles the TextChanged event of the TextBox controls.
  64.    ''' </summary>
  65.    ''' <param name="sender">The source of the event.</param>
  66.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  67.    Friend Sub tb_textchanged(ByVal sender As Object, ByVal e As KeyPressEventArgs) _
  68.    Handles tb1.KeyPress, tb2.KeyPress, cb1.KeyPress
  69.  
  70.        ' Just a crazy message-box to interacts with the raised event.
  71.        MessageBox.Show("No me da la gana que cambies el texto de mis preciosos controles, asi que voy a hacerlos desaparecer!",
  72.                        "Elektro Is Angry '¬¬",
  73.                        MessageBoxButtons.OK, MessageBoxIcon.Stop)
  74.  
  75.        e.Handled = True
  76.  
  77.        ' Searchs the ControlsForm
  78.        Dim f As Form = sender.FindForm
  79.  
  80.        ' ...And close it
  81.        f.Hide()
  82.        ' f.Close()
  83.        ' f.Dispose()
  84.  
  85.    End Sub
  86.  
  87. #End Region
  88.  
  89. End Class

...Que produce este resultado, donde lo de la derecha son 3 textboxes en el interior del Form "transparente":



Saludos
« Última modificación: 31 Marzo 2014, 12:36 pm por Eleкtro » En línea

diegoCmC

Desconectado Desconectado

Mensajes: 177



Ver Perfil
Re: Windows Form transparente
« Respuesta #4 en: 1 Abril 2014, 10:55 am »

Muchas gracias por la ayuda, un ejemplo de lo que quiero hacer son los cuadros en los que metes las coordenadas en autocad al dibujar figuras.

Finalmente me va a quedar mas simple el codigo inicial que tenia en el que paso el Form como argumento al constructor de la clase que genera los textbox
En línea

a todas las que me abrieron su coraza traeles suerte
ya no creo en el amor pero querria volver a verte
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Form semi-transparente en el q se vean los controles??? « 1 2 3 »
Programación Visual Basic
~~ 22 11,678 Último mensaje 20 Diciembre 2006, 01:54 am
por VirucKingX
Abrir un form desde otro form con netbeans en java
Java
murdock_ 3 47,248 Último mensaje 1 Enero 2009, 03:44 am
por sapito169
[Solucionado] Diferencias en Form con fondo transparente en Win7 x64 y x86 (C#)
.NET (C#, VB.NET, ASP)
Xephiro 3 5,844 Último mensaje 22 Marzo 2011, 14:51 pm
por Xephiro
C#.. En Aplicacion de Windows Form
.NET (C#, VB.NET, ASP)
Arimay3 1 3,888 Último mensaje 14 Mayo 2011, 20:12 pm
por Novlucker
Form se ve como Windows XP en Windows 10
.NET (C#, VB.NET, ASP)
P4nd3m0n1um 4 3,259 Último mensaje 30 Abril 2016, 11:12 am
por okik
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines