UserControl/ElementHost Transparent Background - wpf

I need a method that sets the background of the ElementHost completely transparent or so that it does not even render in the first place.
Current Structure
In the background I have a PictureBox.
Over that there is my UserControl (Which you can Download below).
Both the PictureBox and the UserControl have a Width of 150.
As you can see in the Picture above, the UserControl is 100% Invisible.
In the UserControl is an ElementHost with a Width of 120, within that there is a WPF-Content with a Width of 100.
Everything is Transparent, except the ElementHost1.
My Code
UserControl:
Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = &H20
Return cp
End Get
End Property
Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
End Sub
Public Overrides Sub Refresh()
Parent.Invalidate(New Rectangle(Me.Location, Me.Size), True)
End Sub
Public Sub New()
InitializeComponent()
Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True)
Me.BackColor = System.Drawing.Color.Transparent
ElementHost1.BackColor = System.Drawing.Color.Transparent
ElementHost1.BackColorTransparent = True
End Sub
I´ve also tried to create a Custom ElementHost:
Public Class TransElementHost
Inherits ElementHost
Public Sub TransElementHost()
Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True)
Me.BackColorTransparent = True
'Me.BackColor = System.Drawing.Color.FromArgb(0, 0, 0, 0)
End Sub
Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = &H20
Return cp
End Get
End Property
Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
End Sub
Public Overrides Sub Refresh()
Parent.Invalidate(New Rectangle(Me.Location, Me.Size), True)
End Sub
End Class
My SVGTest-UserControl
Does anybody have an idea?

I know it's been really long since this was active, but if you still need it I've (finally) got a code that will draw controls' backgrounds fully transparent.
Just put this code in the control's code. It overrides the OnPaintBackground event:
Protected Overrides Sub OnPaintBackground(e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaintBackground(e)
If Parent IsNot Nothing Then
Dim index As Integer = Parent.Controls.GetChildIndex(Me)
For i As Integer = Parent.Controls.Count - 1 To index + 1 Step -1
Dim c As Control = Parent.Controls(i)
If c.Bounds.IntersectsWith(Bounds) AndAlso c.Visible = True Then
Dim bmp As New Bitmap(c.Width, c.Height, e.Graphics)
c.DrawToBitmap(bmp, c.ClientRectangle)
e.Graphics.TranslateTransform(c.Left - Left, c.Top - Top)
e.Graphics.DrawImageUnscaled(bmp, Point.Empty)
e.Graphics.TranslateTransform(Left - c.Left, Top - c.Top)
bmp.Dispose()
End If
Next
End If
End Sub

It's probably not the best fix, but you could try using the ButtonRenderer class. Put this code either in OnPaintBackground or OnPaint.
If Me.BackColor = Color.Transparent Then
Windows.Forms.ButtonRenderer.DrawParentBackground(e.Graphics, Me.ClientRectangle, Me)
End If
The ButtonRenderer class is used to draw the regular buttons; their border, background, text, image etc.
I used the above code myself to create a custom control with transparent background. (Though I see now that my control inherits from ButtonBase... But the above code is still worth a try).

Related

Add commands for PropertyGrid

I feel that it's something elementary but I can't find out how to add to class commands for PropertyGrid.
There is a sample class (the real classes are much more complex, but I need only the simplest example to implement the required functionality)
Public Class SampleClass
Public Const DefValue = 1
Public Property Value1 As Integer = DefValue
Public Property Value2 As Integer = DefValue
Public Sub Reset()
Value1 = DefValue
Value2 = DefValue
End Sub
End Class
Used In the sample form:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.PropertyGrid1 = New System.Windows.Forms.PropertyGrid()
Me.SuspendLayout()
'
'PropertyGrid1
'
Me.PropertyGrid1.Location = New System.Drawing.Point(242, 98)
Me.PropertyGrid1.Name = "PropertyGrid1"
Me.PropertyGrid1.Size = New System.Drawing.Size(294, 250)
Me.PropertyGrid1.TabIndex = 0
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.PropertyGrid1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Friend WithEvents PropertyGrid1 As PropertyGrid
End Class
An instance is attached to PropertyGrid by the next piece of code:
Public Class Form1
Private Sample As New SampleClass
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PropertyGrid1.SelectedObject = Sample
End Sub
End Class
The goal is to have a link that resets the contents of the instance at bottom of PropertyGrid like in the picture below, I presume that some attribute for a class is required but can't find what attribute.
Thanks for any advice.

How to remove a record from a Listbox control in my WPF application with VB.Net code behind

I know similar questions to mine have been posted before, but I have tried various suggestions and nothing seem to work.
Here is my issue: I get the following error when trying to remove an item\from my listbox control:
Additional information: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
I need help removing an item from a listbox in WPF with VB.Net code-behind.
When I click a row in the listbox, I want to remove that item from the listbox.
I create alist of object 'ToLoadImages' to load into my listbox.
How would I remove the selected item from the list box and from my list ob object 'ToLoadImages'?
See my code below:
'CODE TO LOAD Listbox
Private Sub GetListToLoad(ClaimNo As String)
Dim ta As New ImagesDataSetTableAdapters.usp_SELECT_ImageTableAdapter
Dim dt As ImagesDataSet.usp_SELECT_ImageDataTable = ta.GetData(1, _ClaimNo, True)
Dim dr As DataRow
ListToLoad = New List(Of ToLoadImages)
Dim i As Integer = 0
For Each dr In dt
Dim ImgSource2() As Byte = DirectCast(dr(7), Byte())
Dim stream2 As MemoryStream = New MemoryStream
stream2.Write(ImgSource2, 0, ImgSource2.Length - 1)
stream2.Seek(0, SeekOrigin.Begin)
bitMap2 = New BitmapImage
bitMap2.BeginInit()
bitMap2.StreamSource = stream2
bitMap2.EndInit()
ListToLoad.Add(New ToLoadImages(dr(0), bitMap2))
Next
ImageListBox.ItemsSource = ListToLoad
End Sub
'Code to retrieve selected item from the listbox
'Here is where I want to add the code that will remove the selected item from my listbox and from the List of 'ToLoadImages'.
Private Sub ImageListBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles ImageListBox.SelectionChanged
Try
Dim itemsToLoad As ToLoadImages
itemsToLoad = ImageListBox.SelectedItem
Dim imageID as String = itemsToLoad.ImgID.ToString
Catch ex As Exception
MsgBox("Error encountered.")
End Try
End Sub
Class ToLoadImages
Public Class ToLoadImages
Private m_imgID As Integer
Private m_imageX As BitmapImage
Public Sub New(imgID As Integer, imagex As BitmapImage)
Me.m_imgID = imgID
Me.m_imageX = imagex
End Sub
Public Property ImgID() As Integer
Get
Return m_imgID
End Get
Set(ByVal value As Integer)
m_imgID = value
End Set
End Property
Public Property ImageX() As BitmapImage
Get
Return m_imageX
End Get
Set(ByVal value As BitmapImage)
m_imageX = value
End Set
End Property
End Class
Use ObservableCollection instead of List.
ObservableCollection
updates the changes automatically

Event not firing after item updated, even after re-adding the handler

In my Program Cyrus-Beck algorithm, I have to clip the points. The points inside the clipping window have to be red. The outside is still black.
I represent point in program as rectangle and I give the event handler for delete the point. when I wanted to delete points, points outside the window is working, but points that inside polygon didn't work, event the right-click event not call.
Here is my Point class.
Ignore the Component class, because it just nothing than handler to canvas in the main window
Public Class Points
Inherits Component
Public items As List(Of Point) = New List(Of Point)()
Public rects As List(Of Rectangle) = New List(Of Rectangle)
'add element
Public Overrides Sub Canvas1_MouseMove(sender As Object, e As MouseEventArgs)
canvas.Cursor = Cursors.Pen
End Sub
Public Overrides Sub Canvas1_MouseDown(sender As Object, e As MouseButtonEventArgs)
canvas.Cursor = Cursors.Pen
If e.LeftButton = MouseButtonState.Pressed Then
items.Add(e.GetPosition(canvas))
Dim p As Rectangle = New Rectangle()
p.Width = 3
p.Height = 3
canvas.SetLeft(p, e.GetPosition(canvas).X)
canvas.SetTop(p, e.GetPosition(canvas).Y)
p.Stroke = Brushes.Black
p.Fill = Brushes.Black
rects.Add(p)
End If
End Sub
'deleting element
'this method not calling when the element has updated
Sub point_rightClick(sender As Object, e As MouseButtonEventArgs)
Dim temp As Rectangle = New Rectangle()
temp = DirectCast(sender, Rectangle)
Dim pt As Point = New Point(Controls.Canvas.GetLeft(temp), Controls.Canvas.GetTop(temp))
canvas.Children.Remove(temp)
items.Remove(pt)
rects.Remove(temp)
End Sub
Public Shared Function samePoint(one As Rectangle, two As Rectangle) As Boolean
Return ((Controls.Canvas.GetLeft(one) = Controls.Canvas.GetLeft(two)) And (Controls.Canvas.GetTop(one) = Controls.Canvas.GetTop(two)))
End Function
Public Shared Function samePoint(one As Point, two As Rectangle) As Boolean
Return (one.X = Controls.Canvas.GetLeft(two)) And (one.Y = Controls.Canvas.GetTop(two))
End Function
End Class
To able to delete, I have deleting that represents the status, if deleting is true and currentState = MouseState.Pointer. the code will add handler to all the points (rectangles).
Private Sub chge_pointer_Click(sender As Object, e As RoutedEventArgs) Handles chge_pointer.Click
currentState = MouseState.Pointer
deleting = True
chooseHandler()
End Sub
Private Sub chooseHandler()
If deleting Then
For Each r As Rectangle In points.rects
AddHandler r.MouseRightButtonDown, AddressOf points.point_rightClick
Next
Else
For Each r As Rectangle In points.rects
RemoveHandler r.MouseRightButtonDown, AddressOf points.point_rightClick
Next
End If
End Sub
Before I modified the points to be red, I have to have a loop to check if the position is same, if the position same so edit the points
Dim z As CyrusBeck = New CyrusBeck(clippingWindow)
z.Clip(points.items)
'CyrusBeck has a properties 'points'
'CyrusBeck.points saves the all the point that inside the clipping window
For i As Integer = 0 To points.rects.Count - 1
For Each p As Point In z.points
If CGAProject.Points.samePoint(p, points.rects.Item(i)) Then
Dim temp_r As Rectangle = New Rectangle()
temp_r = points.rects.Item(i)
temp_r.Stroke = Brushes.Red
temp_r.Fill = Brushes.Red
points.rects.Add(temp_r)
points.rects.RemoveAt(i)
End If
Next
Next
when the program reaches this, currentState would Never to be MouseState.Pointer. so if user want to delete a point, user have to be press button chge_pointer so my chge_pointer_Click is called and all my handler would be re-setted again.
Why Rectangle.MouseRightButtonDown is not call when the rectangle has updated?
the rectangles that haven't update call the Rectangle.MouseRightButtonDown event, so I have re-set the handler.
What's worng?
Is there any alternative way so user can delete rectangle inside and outside the window?
Note :
I have resetted the handler just after I assigned back my Rectangle to the list, but it still didn't work.
I also create AddHandler temp_r.MouseRightButtonDown, AddressOf points.point_rightClick just after I assigned back my Rectangle to the list, but it didn't work either.
At the end of your events for clicking, like:
Sub point_rightClick(sender As Object, e As MouseButtonEventArgs)
I think you should have a "handles".
E.g.
Sub point_rightClick(sender As Object, e As MouseButtonEventArgs) Handles point.MouseClick
Without this, the sub will never be called (as it seems is happening).
This method also has no "handles"
Public Overrides Sub Canvas1_MouseDown(sender As Object, e As MouseButtonEventArgs)
and it could be:
Public Overrides Sub Canvas1_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles Canvas1.MouseDown

how to hide my borderless window apps in wpf vb.net using alt+tab

hi guyz i found a code on how to use alt+tab in a borderless window apps in this link
How to hide form from Alt-Tab dialog
but the problem is it was coded in C# so when i convert it to vb.net using c# to vb.net online conversion....
from c# code like these:
protected override CreateParams CreateParams {
get {
// Turn on WS_EX_TOOLWINDOW style bit
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x80;
return cp;
}
}
then i converted to vb.net using the online conversion. and here it goes:
Protected Overrides ReadOnly Property CreateParams() As CreateParams
Get
' Turn on WS_EX_TOOLWINDOW style bit
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or &H80
Return cp
End Get
End Property
So in my code. here it goes:
Imports System.Windows.Forms
Namespace OSOASA
Partial Public Class WindowLoginForm
Protected Overrides ReadOnly Property CreateParams() As CreateParams
Get
' Turn on WS_EX_TOOLWINDOW style bit
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or &H80
Return cp
End Get
End Property
End Class
End Namespace
it gives me 2 error
First:
"Property 'CreateParams' cannot be declared 'Overrides' because it does not oeverride
a property in a base class."
Second:
"'CreateParams' is not a member of 'System.Windows.Window"
Here's some methods to remove a window from Alt + Tab.
Simply call the method Helper.RemoveFromAltTab(Me).
I've tested this code and it successfully works
when the ShowInTaskbar="False" in Window.
Imports System
Imports System.Runtime.InteropServices
Imports System.Windows
Imports System.Windows.Interop
Public Class Helper
Friend Const GwlExstyle As Integer = -20
Friend Const WsExToolwindow As Integer = &H80
<DllImport("user32.dll", EntryPoint:="GetWindowLong", CharSet:=CharSet.Auto)> _
Private Shared Function GetWindowLong32(hWnd As IntPtr, nIndex As Integer) As IntPtr
End Function
<DllImport("user32.dll", EntryPoint:="SetWindowLong", CharSet:=CharSet.Auto)> _
Private Shared Function SetWindowLong(hWnd As IntPtr, nIndex As Integer, value As UInteger) As IntPtr
End Function
Friend Shared Sub RemoveFromAltTab(hwnd As IntPtr)
Dim ws As UInteger = GetWindowLong32(hwnd, GwlExstyle)
SetWindowLong(hwnd, GwlExstyle, ws Or WsExToolwindow)
End Sub
Friend Shared Sub RemoveFromAltTab(w As Window)
RemoveFromAltTab((New WindowInteropHelper(w)).Handle)
End Sub
End Class

WinForm DateTimePicker blues. Is it me?

I want to be able to accept a NULL date using the DateTimePicker control.
The "Checked" property appears to be intended to specify whether the control "holds a date" or now. However, when "unchecked", the date still appears, though it appears disabled. To me, this is distracting. If the intent of the unchecked checkbox is to indicate that there is no date value, why is there ANY date value disable or otherwise that appears in the textbox? It seems to me that if the control is unchecked, the textbox should be EMPTY and that seeing a dimmed date value when the user really wants "no value" is distracting.
If the user toggled the checkbox on, then I would like the ability to place a default value into the textbox.
I am considering creating a usercontrol that toggles between a dateTimePicker control and a textBox, but I hate to go through this trouble.
I tried looking a Telerik's DateTimePicker but trying to get decent null handling functionality out of that control seems worse. I'd love to see a working example of what one of you think is a user-friendly code example with either the std MS or Telerik DateTimePicker control that accepts null input.
I've looked at a few opensource controls, but every time they fix one issue, they introduce others.
EDIT:
See my answer below. It seems to work fine, now I just want to make it part of every DateTimePicker's behavior.
I had the same problem. Well, actually I'm smart enough to understand, but my users had a problem.
I solved by removing the checkbox, and adding 2 radio buttons. Looks something like this now:
(using pseudo UI)
O No value entered
O | 1/1/2010 |V|
The top radiobutton is checked when there is no value (null), the bottom one when there is a value. I do not hide, or disable the bottom control, and users seem to understand.
The downside is, that it takes a lot more space.
PS: Next thing users will complain about is using the scroll-wheel when a combo-box has focus.
Klugey, but it seems to get the job done. If the checkbox is not checked, assume a NULL value.
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
If DateTimePicker1.Checked Then
DateTimePicker1.Format = DateTimePickerFormat.Short 'Or whatever the original format was
Else
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = " "
End If
End Sub
OK, the next question...How do I roll this behavior into a subclassed DateTimePicker? What I want to do is to capture the original values of the Format and CustomFormat properties as set in the Properties window. But, this clearly isn't the way to do it.
Here's my feeble attempt:
Public Class NullableDateTimePicker
Inherits DateTimePicker
Private _OriginalFormat As DateTimePickerFormat
Private _OriginalCustomerFormat As String
Private Sub NullableDateTimePicker_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ValueChanged
If Me.Checked Then
Me.Format = _OriginalFormat
Me.CustomFormat = _OriginalCustomerFormat
Else
Me.Format = DateTimePickerFormat.Custom
Me.CustomFormat = " "
End If
End Sub
Private Sub _DP_FormatChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Static Count As Integer
If Count = 0 Then
_OriginalFormat = Me.Format
_OriginalCustomerFormat = Me.CustomFormat
End If
Count += 1
End Sub
Public Sub New()
AddHandler MyBase.FormatChanged, AddressOf _DP_FormatChanged
End Sub
End Class
I realise this is many years after your initial question but here's a subclass of the Telerik RadDateTimePicker that does what you were asking for:
Imports Telerik.WinControls.UI
Public Class DateTimePickerWithNull
Inherits Telerik.WinControls.UI.RadDateTimePicker
Private ReadOnly _calendar As RadCalendar
Sub New()
Dim calendarBehavior As RadDateTimePickerCalendar = Me.DateTimePickerElement.GetCurrentBehavior()
calendarBehavior.DropDownMinSize = New Size(220, 150)
_calendar = calendarBehavior.Calendar
_calendar.ShowFooter = True
AddHandler _calendar.ClearButton.Click, AddressOf ClearButton_Click
AddHandler _calendar.TodayButton.Click, AddressOf TodayButton_Click
End Sub
Private Sub ClearButton_Click(sender As Object, e As EventArgs)
'Do this to put the calendar away
_calendar.SelectedDate = _calendar.FocusedDate
'Then clear
Me.SetToNullValue()
End Sub
Private Sub TodayButton_Click(sender As Object, e As EventArgs)
_calendar.SelectedDate = _calendar.FocusedDate
End Sub
End Class
To get the value of the picker:
If DateTimePicker1.Value.Date = DateTimePicker1.NullDate Then
Label1.Text = "Null"
Else
Label1.Text = DateTimePicker1.Value.ToLongDateString
End If
A bit tricky to get right. This looked good:
Imports System.ComponentModel
Public Class MyDateTimePicker
Inherits DateTimePicker
Implements ISupportInitialize
Public Sub New()
Me.ShowCheckBox = True
Me.NullDate = True
End Sub
Private CustomFormatBacking As String = ""
Private FormatBacking As DateTimePickerFormat = DateTimePickerFormat.Long
<DefaultValue(True)> _
<Bindable(True)> _
Public Property NullDate() As Boolean
Get
Return Not Me.Checked
End Get
Set(ByVal value As Boolean)
Me.Checked = Not value
End Set
End Property
<DefaultValue("")> _
<Localizable(True)> _
<RefreshProperties(RefreshProperties.Repaint)> _
Public Shadows Property CustomFormat() As String
Get
Return CustomFormatBacking
End Get
Set(ByVal value As String)
CustomFormatBacking = value
If DesignMode Or Not NullDate Then MyBase.CustomFormat = value
End Set
End Property
<RefreshProperties(RefreshProperties.Repaint)> _
Public Shadows Property Format() As DateTimePickerFormat
Get
Return FormatBacking
End Get
Set(ByVal value As DateTimePickerFormat)
FormatBacking = value
If DesignMode Or Not NullDate Then MyBase.Format = value
End Set
End Property
<DefaultValue(true)> _
<Bindable(True)> _
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows Property Checked() As Boolean
Get
Return MyBase.Checked
End Get
Set(ByVal value As Boolean)
MyBase.Checked = value
End Set
End Property
Private Sub updateNullState()
If NullDate and Not DesignMode Then
MyBase.CustomFormat = " "
MyBase.Format = DateTimePickerFormat.Custom
Else
MyBase.CustomFormat = CustomFormatBacking
MyBase.Format = FormatBacking
End If
End Sub
Public Sub BeginInit() Implements System.ComponentModel.ISupportInitialize.BeginInit
End Sub
Public Sub EndInit() Implements System.ComponentModel.ISupportInitialize.EndInit
updateNullState()
End Sub
Protected Overrides Sub OnValueChanged(ByVal eventargs As System.EventArgs)
MyBase.OnValueChanged(eventargs)
updateNullState()
End Sub
End Class

Resources