The embedded resource font is not working properly on the controls.
But it can is used by Graphics object draw something.
First, add fontawesome-webfont.ttf font file with embedded resource.
Then, get font from assembly resources.
Next, assign the font property to the control.
Code here:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Sample
{
public partial class FormSample : Form
{
PrivateFontCollection pfc;
Font font ;
public FormSample()
{
InitializeComponent();
pfc = LoadFontFromResource("Sample.assets.fontawesome-webfont.ttf");
font = new Font(pfc.Families[0], 16, FontStyle.Regular);
this.textBoxControl1.Text = "\uf028 fontawesome";
this.label1.Text = "\uf028 fontawesome";
this.label1.ForeColor = Color.Green;
this.textBoxControl1.ForeColor = Color.Green;
this.label1.Font = font;
this.textBoxControl1.Font = font;
}
private void button1_Click(object sender, EventArgs e)
{
this.label1.Font = font;
this.textBoxControl1.Font = font;
Graphics g = this.CreateGraphics();
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawString("\uf028 fontawesome(GDI+)", font, new SolidBrush(Color.Green), new Point(this.label1.Location.X+10, 80));
g.Dispose();
}
/// <summary>
/// Loads the font from resource.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>PrivateFontCollection.</returns>
public static PrivateFontCollection LoadFontFromResource(string name)
{
PrivateFontCollection pfc = new PrivateFontCollection();
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(name))
{
if (stream == null) return null;
byte[] fontData = new byte[stream.Length];
stream.Read(fontData, 0, (int)stream.Length);
IntPtr ptr = Marshal.AllocHGlobal(fontData.Length);
Marshal.Copy(fontData, 0, ptr, fontData.Length);
pfc.AddMemoryFont(ptr, fontData.Length);
return pfc;
}
}
}
}
This is helpful:Embedded resource font in C# does not work correctly,thanks.
Related
I'm drawing the following Shape in a Canvas.
I would like to highlight it when it's selected by changing its color (the easy part) and drawing an small halo around it:
This is how I did using SASS: http://codepen.io/aaromnido/pen/zKvAwd/
How coud I draw in WPF? Remember that I'm drawing using the Shape's OnRender method.
Set some defaults in constructor.
One of these defaults is Shape.Effect, as it will be animated on MouseEnter event.
Construct VisualStates for Normal , and MouseEnter scenarios.
Change the VisualState of the element using VisualStateManager.GoToElementState() in MouseEnter and MouseLeave event handlers.
You can expose various properties using DPs for customization.
NewShape.cs
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows;
using System.Windows.Media.Effects;
namespace WpfStackOverflow.NewShape
{
public class CNewShape : Shape
{
public CNewShape()
{
// setting the defaults
this.Width = 40;
this.Height = 40;
this.Stroke = new SolidColorBrush() { Color = Colors.Red };
this.StrokeThickness = 5;
this.Effect = new DropShadowEffect() {
Color = Colors.Transparent,
BlurRadius = 1,
Direction = -150,
ShadowDepth = 1
};
// constructing the VisualStates
_constructVisualStates();
// event handlers
this.MouseEnter += CNewShape_MouseEnter;
this.MouseLeave += CNewShape_MouseLeave;
}
#region EventHandlers
void CNewShape_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
VisualStateManager.GoToElementState(this, "VSNormal", false);
}
void CNewShape_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
VisualStateManager.GoToElementState(this, "VSMouseEnter", false);
}
#endregion
#region Overrides
// This needs to be implemented as it is abstract in base class
GeometryGroup geo = new GeometryGroup();
protected override Geometry DefiningGeometry
{
get { return geo; }
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
Pen pen = new Pen(this.Stroke, StrokeThickness);
drawingContext.DrawEllipse(Brushes.Transparent, pen, new Point(Width/2, Height/2), 40, 40);
drawingContext.DrawEllipse(Stroke, null, new Point(Width / 2, Height / 2), 30, 30);
base.OnRender(drawingContext);
}
#endregion
#region Helpers
private void _constructVisualStates()
{
VisualStateGroup vsg1 = new VisualStateGroup();
#region VSNormal (Normal Visual State)
VisualState stateVSNormal = new VisualState() { Name = "VSNormal" };
Storyboard sbVSNormal = new Storyboard();
ObjectAnimationUsingKeyFrames oa = new ObjectAnimationUsingKeyFrames();
Storyboard.SetTargetProperty(oa, new PropertyPath("Effect"));
DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(null);
oa.KeyFrames.Add(dokf);
sbVSNormal.Children.Add(oa);
stateVSNormal.Storyboard = sbVSNormal;
vsg1.States.Add(stateVSNormal);
#endregion
#region VSMouseEnter (MouseEnter Visual State)
VisualState stateVSMouseEnter = new VisualState() { Name = "VSMouseEnter" };
Storyboard sbVSMouseEnter = new Storyboard();
ColorAnimation caStrokeColor = new ColorAnimation();
caStrokeColor.To = (Color)ColorConverter.ConvertFromString("#FF24BCDE");
Storyboard.SetTargetProperty(caStrokeColor, new PropertyPath("(Shape.Stroke).(SolidColorBrush.Color)"));
sbVSMouseEnter.Children.Add(caStrokeColor);
ColorAnimation caEffectColor = new ColorAnimation();
caEffectColor.To = (Color)ColorConverter.ConvertFromString("#FFA4E1F3");
Storyboard.SetTargetProperty(caEffectColor, new PropertyPath("(Shape.Effect).(Color)"));
sbVSMouseEnter.Children.Add(caEffectColor);
DoubleAnimation daBlurRadius = new DoubleAnimation();
daBlurRadius.To = 10;
Storyboard.SetTargetProperty(daBlurRadius, new PropertyPath("(Shape.Effect).(BlurRadius)"));
sbVSMouseEnter.Children.Add(daBlurRadius);
DoubleAnimation daDirection = new DoubleAnimation();
daDirection.To = -190;
Storyboard.SetTargetProperty(daDirection, new PropertyPath("(Shape.Effect).(Direction)"));
sbVSMouseEnter.Children.Add(daDirection);
stateVSMouseEnter.Storyboard = sbVSMouseEnter;
vsg1.States.Add(stateVSMouseEnter);
#endregion
VisualStateManager.GetVisualStateGroups(this).Add(vsg1);
}
#endregion
}
}
Usage
<local:CNewShape Canvas.Left="70" Canvas.Top="52" Stroke="#FF374095" StrokeThickness="10" Width="100" Height="100" />
Output
Quality of the image is bad. On screen actual output looks good.
Whatever your trigger is that your control enters the Highlighted state, in that trigger just set the Effect property. For my test the "trigger" is a property:
public static readonly DependencyProperty ShowShadowProperty =
DependencyProperty.Register ("ShowShadow", typeof (bool), typeof (TestShape), new PropertyMetadata (false, ShowShadowChanged));
public bool ShowShadow
{
get { return (bool)GetValue (ShowShadowProperty); }
set { SetValue (ShowShadowProperty, value); }
}
private static void ShowShadowChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TestShape)d).OnShowShadow ();
}
private void OnShowShadow ()
{
if (ShowShadow)
{
Effect = new DropShadowEffect { Direction = 0, ShadowDepth = 20, BlurRadius = 33, Opacity = 1, Color = Colors.Black};
}
else
{
Effect = null;
}
}
Which means you don't need to do anything in OnRender.
I am working on a project for my Uni, and I am currently stuck on a Pixel Perfect Collision Detection from this website http://www.andybeaulieu.com/Home/tabid/67/EntryID/160/Default.aspx. I have downloded example project that is using this collsion detection and it is working fine even with my own pictures. I have done the same thing in my project and it is not working. Here is the link to my app: https://www.cubby.com/pl/LostInTheMath.zip/_dd23e2c827604c068a3fe63ff42d22b2 could anyone tell me whats wrong with it? Thank you.
Here is the main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
namespace LostInTheMath
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
}
private void UserCntrl_MouseMove(object sender, MouseEventArgs e)
{
Point pt = e.GetPosition(cnvHitTest);
Monkey.SetValue(Canvas.LeftProperty, pt.X);
Monkey.SetValue(Canvas.TopProperty, pt.Y);
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
Image MonkeyShell = Monkey.FindName("imgMonkey") as Image;
Image Mazer = Maze.FindName("imgMaze") as Image;
if (CheckCollision(Monkey, MonkeyShell, Maze, Mazer))
{
Monkey.Width = 1000;
txtStatus.Text = "Collision with XAML Element!";
return;
}
txtStatus.Text = string.Empty;
}
private bool CheckCollision(FrameworkElement control1, FrameworkElement controlElem1, FrameworkElement control2, FrameworkElement controlElem2)
{
// first see if sprite rectangles collide
Rect rect1 = UserControlBounds(control1);
Rect rect2 = UserControlBounds(control2);
rect1.Intersect(rect2);
if (rect1 == Rect.Empty)
{
// no collision - GET OUT!
return false;
}
else
{
bool bCollision = false;
Point ptCheck = new Point();
// NOTE that creating the writeablebitmap is a bit intense
// so we will do this once and store results in Tag property
// in a real game, you might abstract this into a Sprite class.
if (controlElem1 is Image)
controlElem1.Tag = GetWriteableBitmap(control1);
if (controlElem2 is Image)
controlElem2.Tag = GetWriteableBitmap(control2);
// now we do a more accurate pixel hit test
for (int x = Convert.ToInt32(rect1.X); x < Convert.ToInt32(rect1.X + rect1.Width); x++)
{
for (int y = Convert.ToInt32(rect1.Y); y < Convert.ToInt32(rect1.Y + rect1.Height); y++)
{
ptCheck.X = x;
ptCheck.Y = y;
if (CheckCollisionPoint(ptCheck, control1, controlElem1))
if (CheckCollisionPoint(ptCheck, control2, controlElem2))
{
bCollision = true;
break;
}
}
if (bCollision) break;
}
return bCollision;
}
}
public bool CheckCollisionPoint(Point pt, FrameworkElement control, FrameworkElement controlElem)
{
if (controlElem is Image)
{
// NOTE that we saved the WB in the Tag object for performance.
// in a real app, you might abstract this in your sprite class.
WriteableBitmap wb = controlElem.Tag as WriteableBitmap;
int width = wb.PixelWidth;
int height = wb.PixelHeight;
double offSetX = Convert.ToDouble(control.GetValue(Canvas.LeftProperty));
double offSetY = Convert.ToDouble(control.GetValue(Canvas.TopProperty));
pt.X = pt.X - offSetX;
pt.Y = pt.Y - offSetY;
int offset = Convert.ToInt32((width * pt.Y) + pt.X);
return (wb.Pixels[offset] != 0);
}
else
{
List<UIElement> hits = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(pt, controlElem) as List<UIElement>;
return (hits.Contains(controlElem));
}
}
private WriteableBitmap GetWriteableBitmap(FrameworkElement control)
{
WriteableBitmap wb = new WriteableBitmap((int)control.Width, (int)control.Height); ;
wb.Render(control, new TranslateTransform());
wb.Invalidate();
return wb;
}
public Rect UserControlBounds(FrameworkElement control)
{
Point ptTopLeft = new Point(Convert.ToDouble(control.GetValue(Canvas.LeftProperty)), Convert.ToDouble(control.GetValue(Canvas.TopProperty)));
Point ptBottomRight = new Point(Convert.ToDouble(control.GetValue(Canvas.LeftProperty)) + control.Width, Convert.ToDouble(control.GetValue(Canvas.TopProperty)) + control.Height);
return new Rect(ptTopLeft, ptBottomRight);
}
}
}
I have download the code for OpenFileDialog (File Upload function) from Silverlight tutorials website. I am creating a silverlight application using ESRI API and I would like to incorporate the file upload functionality in to it. I have replicated the exact code in to my application there are no errors when I run it, but for some reason my application dosen't execute this line of code "c.OpenWriteAsync(Ub.Uri)"
Edit 2: I notice another thing when I upgraded the general handler (receiver.ashx) which I downloaded it has the following as first line while my generic handler doesn't
<%# WebHandler Language="C#" Class="receiver" %>
I dont know why my code dosent trigger it :(
Here is my Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Markup;
using System.Windows.Shapes;
using System.ComponentModel;
using ESRI.ArcGIS.Client;
using System.Windows.Controls.Primitives;
using System.IO;
using System.IO.IsolatedStorage;
namespace DataTool
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// HtmlPage.RegisterScriptableObject("SilverlightLearn", this);
}
[ScriptableMember]
private void btnService_Click(object sender, RoutedEventArgs e)
{
}
private void btnUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog Dialog = new OpenFileDialog();
Dialog.Multiselect = false;
Dialog.Filter = "All Files|*.*";
bool? SelFil = Dialog.ShowDialog();
if (SelFil != null && SelFil == true)
{
string selectedfilename = Dialog.File.Name;
UploadFile(selectedfilename, Dialog.File.OpenRead());
}
else
{
//do something else
}
}
private void StoreIso(string fileName, Stream data)
{
}
private void UploadFile(string fileName, System.IO.Stream data)
{
// WebClient Wbc = new WebClient();
UriBuilder Ub = new UriBuilder("http://localhost:63461/DataTool/datareceiver.ashx");
Ub.Query = string.Format("filename={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
c.OpenWriteAsync(Ub.Uri);
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
Here is my datareceiver.ashx code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace DataTool.Web
{
/// <summary>
/// Summary description for datareceiver
/// </summary>
public class datareceiver : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
public void SaveFile(Stream st, FileStream fs)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = st.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I have gone through the downloaded sample code and my code STEP BY STEP and found that my code dosent execute the OpenWriteAsync statement. The downloaded code was in .net 3.5 or 3.0 framework and I upgraded it to 4.0.
EDIT:
Please find a sample here https://rapidshare.com/files/459667631/Testing.zip
This is simple , check following code
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
using (StreamReader reader = dlg.SelectedFile.OpenText())
// Store file content in 'text' variable
string text = reader.ReadToEnd();
}
}
C# Example 2: Copy files to the application's isolated storage.
using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
...
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All files (*.*)|*.*";
dlg.EnableMultipleSelection = true;
if (dlg.ShowDialog() == DialogResult.OK) {
// Save all selected files into application's isolated storage
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
foreach (FileDialogFileInfo file in dlg.SelectedFiles) {
using (Stream fileStream = file.OpenRead()) {
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(file.Name, FileMode.Create, iso)) {
// Read and write the data block by block until finish
while(true) {
byte[] buffer = new byte[100001];
int count = fileStream.Read(buffer, 0, buffer.Length);
if (count > 0) {
isoStream.Write(buffer, 0, count);
}
else {
break;
}
}
}
}
}
}
I have a control with a gradiant background. On the MouseDown or MouseUp event I want to capture what color the pixel is immeidately under the mouse pointer. How would I do that?
I created a behavior that can be attached to an Image object to grab the color, which is 100% WPF. Here is the behavior; it could be tweaked to work with any "Visual", not just an Image.
[Note: I hardcoded 96dpi for the creation of RenderTargetBitmap... your milage may vary]
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Company.Solution.Project.Utilities.Behaviors
{
[Description("Used to sample the color under mouse for the image when the mouse is pressed. ")]
public class ImageBehaviorMouseDownPointSampleToColor : Behavior<Image>
{
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register("SelectedColor", typeof(Color),
typeof(ImageBehaviorMouseDownPointSampleToColor),
new UIPropertyMetadata(Colors.White));
public Color SelectedColor
{
get { return (Color)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.MouseMove += AssociatedObject_MouseMove;
AssociatedObject.MouseDown += AssociatedObject_MouseDown;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
}
private void AssociatedObject_MouseDown(object sender, MouseButtonEventArgs e)
{
SamplePixelForColor();
}
private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
SamplePixelForColor();
}
}
private void SamplePixelForColor()
{
// Retrieve the coordinate of the mouse position in relation to the supplied image.
Point point = Mouse.GetPosition(AssociatedObject);
// Use RenderTargetBitmap to get the visual, in case the image has been transformed.
var renderTargetBitmap = new RenderTargetBitmap((int)AssociatedObject.ActualWidth,
(int)AssociatedObject.ActualHeight,
96, 96, PixelFormats.Default);
renderTargetBitmap.Render(AssociatedObject);
// Make sure that the point is within the dimensions of the image.
if ((point.X <= renderTargetBitmap.PixelWidth) && (point.Y <= renderTargetBitmap.PixelHeight))
{
// Create a cropped image at the supplied point coordinates.
var croppedBitmap = new CroppedBitmap(renderTargetBitmap,
new Int32Rect((int)point.X, (int)point.Y, 1, 1));
// Copy the sampled pixel to a byte array.
var pixels = new byte[4];
croppedBitmap.CopyPixels(pixels, 4, 0);
// Assign the sampled color to a SolidColorBrush and return as conversion.
SelectedColor = Color.FromArgb(255, pixels[2], pixels[1], pixels[0]);
}
}
}
}
Can anyone please explain to my why the form in the code below gets out of focus when selecting a treenode in the tree? What should happen is that the form/button should get the focus when the tree disappears like the listview example but it doesn't.
Code example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FocusTest
{
public partial class Form1 : Form
{
#region Generated
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("Item1");
System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("Item2");
System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem("Item3");
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Node0");
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Node1");
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("Node2");
this.button1 = new System.Windows.Forms.Button();
this.listView1 = new System.Windows.Forms.ListView();
this.button2 = new System.Windows.Forms.Button();
this.treeView1 = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// listView1
//
this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1,
listViewItem2,
listViewItem3
});
this.listView1.Location = new System.Drawing.Point(12, 41);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(121, 97);
this.listView1.TabIndex = 1;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.Visible = false;
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
this.listView1.View = View.List;
//
// button2
//
this.button2.Location = new System.Drawing.Point(310, 11);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// treeView1
//
this.treeView1.Location = new System.Drawing.Point(310, 41);
this.treeView1.Name = "treeView1";
treeNode1.Name = "Node0";
treeNode1.Text = "Node0";
treeNode2.Name = "Node1";
treeNode2.Text = "Node1";
treeNode3.Name = "Node2";
treeNode3.Text = "Node2";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode2,
treeNode3});
this.treeView1.Size = new System.Drawing.Size(121, 97);
this.treeView1.TabIndex = 3;
this.treeView1.Visible = false;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(760, 409);
this.Controls.Add(this.treeView1);
this.Controls.Add(this.button2);
this.Controls.Add(this.listView1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TreeView treeView1;
#endregion
public Form1()
{
InitializeComponent();
}
#region TreeView
private void button2_Click(object sender, EventArgs e)
{
ToggleTreeView();
}
private void ToggleTreeView()
{
if (treeView1.Visible)
{
Controls.Remove(treeView1);
treeView1.Visible = false;
}
else
{
Controls.Add(treeView1);
treeView1.Size = new Size(300, 400);
treeView1.Location = PointToClient(PointToScreen(new System.Drawing.Point(button2.Location.X, button2.Location.Y + button2.Height)));
this.treeView1.BringToFront();
treeView1.Visible = true;
treeView1.Select();
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
ToggleTreeView();
}
#endregion
#region ListView
private void button1_Click(object sender, EventArgs e)
{
ToggleListView();
}
private void ToggleListView()
{
if (listView1.Visible)
{
Controls.Remove(listView1);
listView1.Visible = false;
}
else
{
Controls.Add(listView1);
listView1.Size = new Size(300, 400);
listView1.Location = PointToClient(PointToScreen(new System.Drawing.Point(button1.Location.X, button1.Location.Y + button1.Height)));
this.listView1.BringToFront();
listView1.Visible = true;
listView1.Select();
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.Visible)
ToggleListView();
}
#endregion
}
}
Here is the problem and the fix.
TreeView re-grabs focus on Ctrl+Click
I can't explain why the form loses focus, but the problem seems to be the Controls.Remove(treeView1); line. If you remove the Controls.Remove and Controls.Add lines, then it seems to behave better.
Is there a reason why you are removing the treeView from the list of control? Just setting the visibility flag to false will cause the treeView to disappear after the user makes their selection.
EDIT:
In response to your comment:
My guess is that after treeView1_AfterSelect is called, the TreeView is setting focus to itself. Which in your code is impossible because you've removed the control from the form.
To test this theory, I added a timer, replaced the code with:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
ToggleTreeView();
timer1.Stop();
timer1.Enabled = false;
}
Now it works fine. So I'm guessing that the TreeView is calling this.Focus after it has fired the AfterSelect event. (That is just a guess, maybe someone else knows more about the internals them me:) )
And the reason why this is working with the ListView, is that it does not set focus to itself after listView1_SelectedIndexChanged.