How to add dynamically created hyperlink to stack panel programmatically wpf - c#

i am creating hyperlinks and want to add it to stack panel.
for (int i = 1; i <= links.Length; i++)
{
Hyperlink hyperlink = new Hyperlink()
{
NavigateUri = new Uri(links[i - 1])
};
}
hyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(this.Hyperlink_RequestNavigate);
mainControl.Children.Add(hyperlink);
it gives me error -
cannot convert to system.windows.documents.hyperlink to system.windows.uielement.
i understand the namespace error but didn't find resolution because in uielement i dint find hyperlink.

Use LinkLabel instead of HyperLink
Samples:
using System;
using System.Drawing;
using System.Windows.Forms;
public class LinkLabelAddLink : Form {
LinkLabel lnkLA = new LinkLabel();
public LinkLabelAddLink(){
Size = new Size(300,250);
lnkLA.Parent = this;
lnkLA.Text = "StackOverflow.com";
lnkLA.Location = new Point(0,25);
lnkLA.AutoSize = true;
lnkLA.BorderStyle = BorderStyle.None;
lnkLA.Links.Add(0,7,"www.stackoverflow.com");
lnkLA.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(lnkLA_LinkClicked);
}
static void Main()
{
Application.Run(new LinkLabelAddLink());
}
private void lnkLA_LinkClicked(object sender,LinkLabelLinkClickedEventArgs e)
{
lnkLA.LinkVisited = true;
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}
}
PS: You need atleast .NET 4.5

Related

How can I create big empty white box and write some text in the middle of it?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyTest
{
public partial class Form1 : Form
{
private int x, y;
private int gap = 0;
private int startingY = 150;
private GroupBox lastGB = null;
public Form1()
{
InitializeComponent();
GroupBox gb = new GroupBox();
gb.Location = new Point(100, (lastGB == null ? startingY : lastGB.Bounds.Bottom));
gb.Size = new Size(1220, 400);
gb.BackColor = SystemColors.Window;
gb.Text = "";
gb.Font = new Font("Colonna MT", 12);
this.Controls.Add(gb);
}
It's creating a small line on the top of the groupbox and I don't want this line to show.
And I want to write some text on it in the middle of it.
How can I make it just complete white ? And how to write some text in the middle on the groupbox ?
The main idea is to create over the form a white sheet or box with text inside that's it.
It looks like your intention is to put subsequent boxes just below the last box. As mentioned, a Label would probably be best. I'd also move that code to a method you can call over and over to keep from repeating code elsewhere. You could pass a message to display in the Label. Also, don't forget to update the reference to the "last box" when ever you create a new one:
public partial class Form1 : Form
{
private int x, y;
private int gap = 0;
private int startingY = 150;
private Label lastLbl = null;
public Form1()
{
InitializeComponent();
AddLabel("Hello World");
}
private void button1_Click(object sender, EventArgs e)
{
AddLabel(DateTime.Now.ToString());
}
private void AddLabel(String msg)
{
Label lbl = new Label();
lbl.Location = new Point(100, (lastLbl == null ? startingY : lastLbl.Bounds.Bottom));
lbl.Size = new Size(1220, 400);
lbl.BackColor = Color.White;
lbl.Text = msg;
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.Font = new Font("Colonna MT", 12);
this.Controls.Add(lbl);
lastLbl = lbl;
}
}

TabControl Padding causes hidden Controls in TabPage to re-order incorrectly

The controls with Handles not yet created seem to be pushed to the bottom of their Parent Control when the TabControl's Padding property is changed. Looking at the .NET source code, Padding makes a call to RecreateHandle();, which seems to have something to do with it.
Below is code that illustrates the problem. Each checkbox has a corresponding label just below it. Some of the labels are visible at the start, some are hidden. Checking the person0 checkbox makes the person0 label appear, but incorrectly at the bottom. Instead, the person0 label should appear just underneath the person0 checkbox, which is the order it was added to the FlowLayoutPanel. See screenshot.
The code provides a bool doWorkaround option, but there must be a better way. Forcing all the Handles to be created using CreateControl() seems not correct either.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication3 {
public class TabControl3 : TabControl {
private bool doWorkaround = false; // set to true to prevent the bug
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
int h = (int) this.Font.Height;
SetPadding(new Point(h, h)); // calling this causes the Controls to re-order incorrectly
}
///<summary>Setting the padding causes the TabControl to recreate all the handles, which causes the hidden handleless controls to rearrange.</summary>
public virtual void SetPadding(Point pt) {
// Workaround solution: remove all controls from tab pages and then add them back after.
int n = TabPages.Count;
Control[][] arr = null;
if (doWorkaround) {
arr = new Control[n][];
for (int i = 0; i < n; i++) {
TabPage tp = TabPages[i];
arr[i] = tp.Controls.Cast<Control>().ToArray();
tp.Controls.Clear();
}
}
this.Padding = pt; // in the .NET source code, setting Padding calls RecreateHandle()
if (doWorkaround) {
for (int i = 0; i < n; i++)
TabPages[i].Controls.AddRange(arr[i]);
}
}
}
public class CheckBox2 : CheckBox {
public CheckBox2(String text, bool isChecked = false) : base() {
this.Text = text;
this.AutoSize = true;
this.Checked = isChecked;
}
}
public class Label2 : Label {
public Label2(String text) : base() {
this.Text = text;
this.AutoSize = true;
}
}
public class MyForm : Form {
TabControl tc = new TabControl3 { Dock = DockStyle.Fill };
public MyForm() {
this.Size = new System.Drawing.Size(600, 800);
this.StartPosition = FormStartPosition.CenterScreen;
TabPage tp1 = new TabPage("Page1");
FlowLayoutPanel p = new FlowLayoutPanel { FlowDirection = System.Windows.Forms.FlowDirection.TopDown, Dock = DockStyle.Fill };
p.Controls.Add(new CheckBox2("Person0"));
p.Controls.Add(new Label2("Person0") { Visible = false });
p.Controls.Add(new CheckBox2("Person1", true));
p.Controls.Add(new Label2("Person1"));
p.Controls.Add(new CheckBox2("Person2", true));
p.Controls.Add(new Label2("Person2"));
p.Controls.Add(new CheckBox2("Person3"));
p.Controls.Add(new Label2("Person3") { Visible = false });
p.Controls.Add(new CheckBox2("Person4"));
p.Controls.Add(new Label2("Person4") { Visible = false });
for (int i = 0; i < p.Controls.Count; i += 2) {
CheckBox cb = (CheckBox) p.Controls[i];
Label lb = (Label) p.Controls[i+1];
cb.CheckedChanged += delegate {
bool b = cb.Checked;
lb.Visible = b;
};
}
tp1.Controls.Add(p);
tc.TabPages.Add(tp1);
Controls.Add(tc);
}
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
this.Font = SystemFonts.MenuFont; // to trigger the bug
}
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}
}
I tested using .NET 3.5, 4, 4.52 and saw the same behavior in all three.

C# Adding an array of RichTextBoxes to an array of TabPages in a for loop

And my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace inform
{
public partial class Form1 : Form
{
public static TabPage[] TabPages = new TabPage[20];
public static RichTextBox[] TextBoxes = new RichTextBox[20];
public Form1()
{
InitializeComponent();
TabControl.TabPages.Clear();
for (int x = 0; x < 19; x++)
{
TabPages[x].Controls.Add(TextBoxes[x]); //ERROR HERE
//Object reference not set to an instance of an object.
TabControl.TabPages.Add(TabPages[x]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
I am trying to make a basic typing program that uses a tabcontrol to organize each richtextbox in an array. But when I run the program it returns
Object reference not set to an instance of an object.
I have made an array of RichTextBoxes and also TabPages which can both hold 20 elements(is that the right word?) but a problem occurs. The function for Control.Add() is suppose to take a control value.
The for loop is meant to go through each TabPage and add the correct RichTextBox to it.
I have gone onto MSDN to see what they have but all they have is
tabPage1.Controls.Add(new Button());
instead of my:
TabPages[x].Controls.Add(TextBoxes[x]);
But even then it does not work, I have done this before but without the the array, the last one I did capped out at 6 tabs and I wanted to make more.
I tried reading some pages on the internet but nothing seemed to work, I would be grateful for any help.
you have to write something like this
public partial class Form1 : Form
{
public static TabPage[] TabPages = new TabPage[20];
public static RichTextBox[] TextBoxes = new RichTextBox[20];
public Form1()
{
InitializeComponent();
tabControl1.TabPages.Clear();
for (int x = 0; x < 19; x++)
{
TabPages[x] = new TabPage();
TabPages[x].Controls.Add(TextBoxes[x]); //ERROR HERE
//Object reference not set to an instance of an object.
tabControl1.TabPages.Add(TabPages[x]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
try this
for (int a = 0; a < 20;a++ )
{
RichTextBox textBox = new RichTextBox();
TextBoxes[a] = textBox;
TabPage tabPage = new TabPage();
TabPages[a] = tabPage;
}
for (int x = 0; x < 19; x++)
{
TabPages[x].Controls.Add(t);
TabControl.TabPages.Add(TabPages[x]);
}

Coloring text using reflection

I'm trying to make a simple text editor that colors text in real time. I also must use DLL and Reflection for this.
I want to color the text while user typing. For that reason I have a checkbox. If it checked the text will be colored while user is typing (Real Time).
I've wrote a DLL file to do that.
Anyway, I'm very new to reflection thing.
The question:
I would want to ask you guys for your professional advice whether what I've wrote can be called "using reflection" or not? and if it's not, can point me what is wrong?
Here is my code (I've removed many things from it so the code will reflect the question but there might be leftovers)
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
namespace Editor
{
public class MainForm : Form
{
//Declaration of Controls
private RichTextBox EditRichTextBox;
private CheckBox chkBox;
private int flag = 0;
private Button[] PlugButton;
public string[] PluginNames;
private int NumofPlugins;
public MainForm()
{
//Initialization of Controls
this.EditRichTextBox = new RichTextBox();
this.ErrorTextBox = new RichTextBox();
this.chkBox = new CheckBox();
//Form
this.ClientSize = new Size(700, 500);
this.Name = "MainForm";
this.Text = "C# Editor";
//EditRichTextBox
this.EditRichTextBox.Location = new Point(20, 20);
this.EditRichTextBox.Name = "EditRichTextBox";
this.EditRichTextBox.Size = new Size(this.Width - 150, 300);
this.EditRichTextBox.AcceptsTab = true;
this.EditRichTextBox.Multiline = true;
//Controls on the Form
this.Controls.Add(this.ButtonCompilelib);
this.Controls.Add(this.ButtonCompile);
this.Controls.Add(this.ButtonRun);
this.Controls.Add(this.EditRichTextBox);
this.Controls.Add(this.ErrorTextBox);
this.Controls.Add(this.chkBox);
//CheckBox
this.chkBox.Location = new Point(600,300);
this.chkBox.Name = "chkBox";
this.chkBox.Text = "Color";
};
//My checkbox handler
this.chkBox.Click += (sender,e) =>
{
if(flag == 0)
{
flag = 1;
MessageBox.Show("Coloring Text");
}
else
flag = 0;
};
//My TextBox handler
this.EditRichTextBox.KeyPress += (sender,e) =>
{
try
{
string tmp = Environment.CurrentDirectory + "\\" + "mydll" + ".dll"; Assembly a = Assembly.LoadFrom(tmp);
Type t = a.GetType("MyPlugIn.colorclass");
MethodInfo mi = t.GetMethod("color");
Object obj = Activator.CreateInstance(t);
Object[] Params = new Object[5];
Params[0] = EditRichTextBox.Text;
Params[1] = EditRichTextBox.Handle;
Params[2] = ErrorTextBox.Handle;
Params[3] = EditRichTextBox;
Params[4] = flag;
mi.Invoke(obj, Params);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
};
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
}
And this is the DLL file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace MyPlugIn
{
public class colorclass
{
public void color(string Text, Object Hndl_Text, Object Hndl_Err, RichTextBox box,int flag)
{
if (flag == 1)
{
int start = box.TextLength;
int end = box.TextLength;
//Textbox may transform chars, so (end-start) != text.Length
box.Select(start, end - start);
{
box.SelectionColor = Color.Blue;
}
box.SelectionLength = 0; // clear
}
}
}
}
Yes, your code uses Reflection. These lines are an example:
Type t = a.GetType("MyPlugIn.colorclass");
MethodInfo mi = t.GetMethod("color");
Object obj = Activator.CreateInstance(t);
Whether is the best approach or not, or whether it's necessary for this task, it's a different topic.

Programmatically add toolbar and their contents in c#

I am a absolute beginner with a simple question(c# . i want to create a toolbar at runtime and their events . I am using visual studio 2008 , .net framework 3.5 , C# .
For example, in you form class you can make some like this:
ToolStrip toolStrip2 = new ToolStrip();
toolStrip2.Items.Add(new ToolStripDropDownButton());
toolStrip2.Dock = DockStyle.Bottom;
this.Controls.Add(toolStrip2);
using System;
using System.IO;
using System.Windows.Forms;
namespace DynamicToolStrip
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DynamicToolStripForm());
}
class DynamicToolStripForm : Form
{
ToolStrip m_toolstrip = new ToolStrip();
public DynamicToolStripForm()
{
Controls.Add(m_toolstrip);
AddToolStripButtons();
}
void AddToolStripButtons()
{
const int iMAX_FILES = 5;
string[] astrFiles = Directory.GetFiles(#"C:\");
for (int i = 0; i < iMAX_FILES; i++)
{
string strFile = astrFiles[i];
ToolStripButton tsb = new ToolStripButton();
tsb.Text = Path.GetFileName(strFile);
tsb.Tag = strFile;
tsb.Click += new EventHandler(tsb_Click);
m_toolstrip.Items.Add(tsb);
}
}
void tsb_Click(object sender, EventArgs e)
{
ToolStripButton tsb = sender as ToolStripButton;
if (tsb != null && tsb.Tag != null)
MessageBox.Show(String.Format("Hello im the {0} button", tsb.Tag.ToString()));
}
}
}
}

Categories