How to override Control.Invalidate() method? - c#

I use OwnerDrawAll properties for my control:
this.customTreeView.DrawMode =System.Windows.Forms.TreeViewDrawMode.OwnerDrawAll;
this.customTreeView.DrawNode +=
new System.Windows.Forms.DrawTreeNodeEventHandler(customTreeView_DrawNode);
private void customTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e) {
if(!myComboBoxChanged) { // Draw the whole control(tree and info)
drawNode(e);
drawInfo(e);
} else { // Draw only info
drawInfo(e);
}
}
Then I use text changed event:
private void cBox_TextChanged(object sender, EventArgs e)
{
text = cBox.Text; // I need this in drawInfo()
myComboBoxChanged = true;
this.customTreeView.Invalidate(); // It doesn't do what I want
myComboBoxChanged = false;
}
Here Invalidate() method redrawing the whole tree, how can I fix this so only drawInfo() will be called ?

the better way is to create your own TreeView Class and encapsulate all of your methods and properties so :
public class MyTreeView : TreeView
{
public bool TextBoxChanged { get; set; }
public MyTreeView()
{
DrawMode = TreeViewDrawMode.OwnerDrawAll;
DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(customTreeView_DrawNode);
}
protected override void OnInvalidated(InvalidateEventArgs e)
{
//comment the below line to create your own Invalidate
//base.OnInvalidated(e);
}
private void customTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
if (!TextBoxChanged)
{ // Draw the whole control(tree and info)
drawNode(e);
drawInfo(e);
}
else
{ // Draw only info
drawInfo(e);
}
}
private void drawNode(DrawTreeNodeEventArgs e)
{
//...........
}
private void drawInfo(DrawTreeNodeEventArgs e)
{
//...........
}
}

Related

Manipulating similar objects in a form using another form

I am new to C# and I want to utilize the forms with one another.
I have 2 forms. (1)MMCMLibrary_home and (2)MMCMLibrary_reserve.
In this project, I'm in the stage of changing the label background colors in Form 1 but can't seem to utilize Form 2 to process it.
These are my necessary codes so far:
FORM 1
namespace MMCM_Library
{
public partial class MMCMLibrary_home : Form
{
public static MMCMLibrary_home instance;
//DCR1 Labels
public Label lbl1_1;
public Label lbl1_2;
public Label lbl1_3;
public Label lbl1_4;
public MMCMLibrary_home()
{
InitializeComponent();
instance = this;
lbl1_1 = lblDCR1_9;
lbl1_2 = lblDCR2_11;
lbl1_3 = lblDCR1_1;
lbl1_4 = lblDCR1_3;
public void btnDCR1_Click(object sender, EventArgs e)
{
var reserveDCR1 = new MMCMLibrary_reserve();
reserveDCR1.Show();
}
public void btnDCR2_Click(object sender, EventArgs e)
{
var reserveDCR2 = new MMCMLibrary_reserve();
reserveDCR2.Show();
}
public void btnDCR3_Click(object sender, EventArgs e)
{
var reserveDCR3 = new MMCMLibrary_reserve();
reserveDCR3.Show();
}
public void btnDCR4_Click(object sender, EventArgs e)
{
var reserveDCR4 = new MMCMLibrary_reserve();
reserveDCR4.Show();
}
}
}
FORM 2
when I click any reserve now button in form 1 it will open form 2. However, if I pick a radio button, the background change will always be applied to Discussion Room 1 even I reserved for discussion room 2
namespace MMCM_Library
{
public partial class MMCMLibrary_reserve : Form
{
public static MMCMLibrary_reserve instance;
public MMCMLibrary_reserve()
{
InitializeComponent();
instance = this;
}
private void MMCMLibrary_reserve_Load(object sender, EventArgs e)
{
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
}
private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged_1(object sender, EventArgs e)
{
}
private void btnDCR1_Click(object sender, EventArgs e)
{
}
public void btnDCRoomsReserve_Click(object sender, EventArgs e)
{
if (rbtn9.Checked)
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
}
}
}
Can you help me to device an efficient way to solve this. Can you also suggest a database method suitable for my beginner project.
You've said that:
the background change will always be applied to Discussion Room 1
Well, yes. It seems you don't pass specific object into Form2. There's strightforward:
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
So you'll be always changing backcolor of lbl1_1 of your Form1. What needs to be done is to indicate which room has been selected. You can assign room after you click the button by passing the int parameter:
public void btnDCR1_Click(object sender, EventArgs e)
{
var reserveDCR1 = new MMCMLibrary_reserve(1);
reserveDCR1.Show();
}
or:
public void btnDCR2_Click(object sender, EventArgs e)
{
var reserveDCR2 = new MMCMLibrary_reserve(2);
reserveDCR2.Show();
}
Then, in Form2, at the very top, add something like:
int room; to be able to assign the room number in Form2:
public MMCMLibrary_reserve(int roomNumber)
{
InitializeComponent();
room = roomNumber;
instance = this;
}
And then you could just select room you clicked, by:
public void btnDCRoomsReserve_Click(object sender, EventArgs e)
{
if (rbtn9.Checked)
{
if(room == 1)
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
else if(room == 2)
{
MMCMLibrary_home.instance.lbl1_2.BackColor = System.Drawing.Color.Red;
}
else if(room == 3)
{
MMCMLibrary_home.instance.lbl1_3.BackColor = System.Drawing.Color.Red;
}
else if(room == 4)
{
MMCMLibrary_home.instance.lbl1_4.BackColor = System.Drawing.Color.Red;
}
}
else if(radioButton2.Checked)
{
//etc.
}
else if(radioButton3.Checked)
{
//etc.
}
else if(radioButton4.Checked)
{
//etc.
}
}
I think that was the problem. Try it and let us know.

C# UserControl Button click adds items to listbox from form1

I'm working on a C# app,that searches for song names on youtube (using youtube api) and displaying the data, I have a custom SongItem (UserControl) and I add them to a FlowLayoutControl. I added a "Favourite" button to the UserControl, and I need that to add itself to another FlowLayoutControl that's the Favourited song list, but I can't get that working, I can't have multiple base classes in the UserControl,and adding a public method to Form1, doesn't solve my issue, (it's not adding anything,tried it with listbox,but nothing).
I'm really stuck here,if someone can at least suggest something I would rly appreciate it.
Here is my SongItem
[Serializable]
public partial class SongItem : UserControl,Form
{
private String songName = "Song Name";
private String artistName = "Artist Name";
private Image thumbNail;
private String length;
private int maxLengthSongName = 25;
private int maxLengthArtistName = 25;
private Color colorHoverOn = Color.FromArgb(53,53,53);
private Color colorNormal = Color.FromArgb(53,53,53);
private SongData songData;
public SongItem()
{
InitializeComponent();
this.MouseClick += Control_MouseClick;
MouseEvents(this);
}
private void SongItem_Load(object sender, EventArgs e)
{
try
{
LoadData();
}
catch { }
LoadDataToUI();
}
#region GettersAndSetters
public int MaxLengthSongName
{
get { return maxLengthSongName; }
set { maxLengthSongName = value; }
}
public int MaxLengthArtistName
{
get { return maxLengthArtistName; }
set { maxLengthArtistName = value; }
}
public Color ColorHoverOn
{
get { return colorHoverOn; }
set { colorHoverOn = value; }
}
public Color ColorNormal
{
get { return colorNormal; }
set { colorNormal = value; }
}
public SongData SongData {
get{return songData; }
set { songData = value; }
}
#endregion
public void LoadData()
{
songName = songData.SongName;
artistName = songData.ArtistName;
thumbNail = songData.ThumbNail;
length = songData.Length;
}
void MouseEvents(Control container)
{
foreach (Control c in container.Controls)
{
c.MouseEnter += (s, e) => SongItem_MouseEnter(e);
c.MouseLeave += (s, e) => SongItem_MouseLeave(e);
c.MouseClick += Control_MouseClick;
MouseEvents(c);
};
}
private void SongNameLbl_MouseHover(object sender, EventArgs e)
{
if (songName.Length > maxLengthSongName) {
toolTip1.SetToolTip(songNameLbl, songName);
}
}
private void ArtistNameLbl_MouseHover(object sender, EventArgs e)
{
if (artistName.Length > maxLengthArtistName) {
toolTip1.SetToolTip(artistNameLbl, artistName);
}
}
private void SongNameLbl_Click(object sender, EventArgs e)
{
Clipboard.SetText(artistName + " " +songName);
}
#endregion
#region CurrentlySelected
public event EventHandler<EventArgs> WasClicked;
private void Control_MouseClick(object sender, MouseEventArgs e)
{
var wasClicked = WasClicked;
if (wasClicked != null)
{
WasClicked(this, EventArgs.Empty);
}
IsSelected = true;
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
this.BorderStyle = IsSelected ? BorderStyle.FixedSingle : BorderStyle.None;
}
}
#endregion
private void Fovourite_Click(object sender, EventArgs e)
{
Main newMain = new Main();
// newMain.AddSongToFavorite();
newMain.listBox1.Items.Add("Test");
}
}
}
Here is the the Form1 code
public void AddSongToFavorite() {
listBox1.Items.Add("Test");
//songList2.AddSong("Dire Straits - Sultans Of Swing");
MessageBox.Show("Hello", "Test");
// flowLayoutPanel1.Controls.Add(song);
}
Message shows up,but nothing else
I add the SongItem from another class
public partial class SongList : FlowLayoutPanel
{
public SongList()
{
InitializeComponent();
SongList_Load();
}
private void SongList_Load()
{
this.AutoScroll = true;
this.FlowDirection = FlowDirection.TopDown;
this.AutoSize = false;
this.WrapContents = false;
}
public async void AddSong(String songName) {
SongData song = await YoutubeSearch.GetSongInfo(songName);
// SongData song = XmlSerialization.ReadFromXmlFile<SongData>(Application.StartupPath + #"\test.txt");
SongItem songItem = new SongItem { SongData = song };
songItem.WasClicked += UsersGrid_WasClicked;
this.Controls.Add(songItem);
}
I fixed the problem by creating an EventHandler
In the main I created this public void
public void FavoriteWasClicked(object sender, EventArgs e) {
if (sender is SongItem)
{
songList2.AddSong(((SongItem)sender).SongData);
}
}
and on Form1 load I added (songList1 is the FlowLayoutPanel already added in the Form1 designer)
songList1.List_FavoriteWasClicked += FavoriteWasClicked;
I added this line to the FlowLayoutPanel class I created
public event EventHandler<EventArgs> List_FavoriteWasClicked;
and when creating new Controls(SongItems inside it)(Still part of FlowLayoutPanel)
public void AddSong(SongData song)
{
SongItem songItem = new SongItem { SongData = song };
songItem.FavoriteWasClicked += List_FavoriteWasClicked; ()
this.Controls.Add(songItem);
}
And now on the SongItem I created the custom event
public event EventHandler<EventArgs> FavoriteWasClicked;
and on the button I wanted to be the press to add to favorite list I added the following
FavoriteWasClicked(this, EventArgs.Empty);
Now when I press the button to add one Song to the liked/favorited list it's actually adding it.

How to check Button clicked in general methode?

I have tried with below
public partial class PaymentSearch : System.Web.UI.Page
{
private bool button1WasClicked = false;
protected void linkToday_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)
{
gridAllPaymentBind(1);
}
public void gridAllPaymentBind(int pageIndex)
{
if (button1WasClicked == true)
{
result = 3;
command.Parameters.AddWithValue("#result", result);
}
}
but in 'gridAllPaymentBind' methode ' button1WasClicked' getting false value where I alredy clicked link button before dropdown list change event fire.
try like below...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack == true)
{
Session["button1WasClicked "] = false;
}
}
protected void linkToday_Click(object sender, EventArgs e)
{
Session["button1WasClicked "] = true;
}
protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)
{
gridAllPaymentBind(1);
}
public void gridAllPaymentBind(int pageIndex)
{
bool button1WasClicked = (bool)Session["button1WasClicked "];
if (button1WasClicked == true)
{
result = 3;
command.Parameters.AddWithValue("#result", result);
}
}
hope this will help you..good luck.
ASP.NET by nature is stateless so the variable value will not persist between postbacks. So to make it persistent you can use either a Session or ViewState.
public partial class PaymentSearch : System.Web.UI.Page
{
private bool button1WasClicked
{
get { return (bool)Session["button1WasClicked"]; }
set { Session["button1WasClicked"] = value; }
}
protected void linkToday_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)
{
gridAllPaymentBind(1);
}
public void gridAllPaymentBind(int pageIndex)
{
if (button1WasClicked == true)
{
result = 3;
command.Parameters.AddWithValue("#result", result);
}
}
}

Transmitting events from a Winform to another in C#

How can I click a Button(to generate a color) in one form and change text color in a RichTextBox in a another form? Thanks in advance. (Newbie trying to understand C#)
Some code:
1.WinForm
public delegate void ColorWindowEvent(Object sender, SecondrWindowEventArgs e);
public partial class ColorWindow : Form
{
public event ColorWindowEvent myEventHandler;
public ColorWindow ()
{
InitializeComponent();
}
public void MyEvent(Object sender, ColorWindowEventArgs e)
{
string s = "";
myEventHandler(this, new SecondWindowEventArgs(s));
}
private void btnRed_Click(object sender, EventArgs e)
{
Color c = Color.Red;
string s = c.ToString();
this.Close();
}
private void btnBlue_Click(object sender, EventArgs e)
{
Color c = Color.Blue;
string str = c.ToString();
this.Close();
}
private void btnGreen_Click(object sender, EventArgs e)
{
Color c = Color.Green;
string s = c.ToString();
this.Close();
}
}
public class SecondWindowEventArgs : EventArgs
{
private string s;
public SecondWindowEventArgs(string _s)
{
s = _s;
}
#region
public string S
{
get;
set;
}
#endregion
}
2.WinForm
public delegate void SecondWindowEvent(Object sender, FirstWindowEventArgs e);
public partial class SecondWindow : Form
{
public event SecondWindowEvent myEventHandler;
private string s;
public SecondWindow(String _s)
{
s = _s;
InitializeComponent();
}
public void MyEvent(Object sender, FirstWindowEventArgs e)
{
string str = rtf2.Text;
if (str != null)
{
myEventHandler(this, new FirstWindowEventArgs(str));
}
}
private void btnQuit_Click(object sender, EventArgs e)
{
this.Close();
}
private void rtf2_TextChanged(object sender, EventArgs e)
{
if (myEventHandler != null)
{
myEventHandler(this, new FirstWindowEventArgs(rtf2.Text.Substring(rtf2.Text.Length - 1)));
rtf2.ForeColor = Color.FromName(e.ToString());
}
}
private void btnClearText_Click(object sender, EventArgs e)
{
rtf2.Text = " ";
}
private void rtf2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Escape)
{
FargeVindu fargeVindu = new FargeVindu();
fargeVindu.minEventHandler += new FargeVinduEvent(fargeVindu_minEventHandler);
fargeVindu.Show();
}
else if (e.KeyData == Keys.Delete)
{
}
}
protected void ColorWindow_myEventHandler(object sender, SecondWindowEventArgs e)
{
rtf2.ForeColor = Color.FromName(s);
}
Random random = new Random();
private void SecondWindow_Load(object sender, EventArgs e)
{
lblText.ForeColor = Color.FromArgb(random.Next(255),
random.Next(255), random.Next(255));
}
public Color getColor
{
get;
set;
}
}
3.WinForm
public partial class FirstWindow : Form
{
public FirstWindow()
{
InitializeComponent();
}
private void btnQuit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClick_Click(object sender, EventArgs e)
{
string str = " ";
SecondWindow secondWindow = new SecondWindow (str);
secondWindow.myEventHandler += new SecondWindowEvent(secondWindow_myEventHandler);
secondWindow.Show();
}
protected void secondWindow_myEventHandler(object sender, FirstWindowEventArgs e)
{
rtf1.AppendText(String.Format(e.Tekst));
}
public void btnClearText_Click(object sender, EventArgs e)
{
rtf1.Text = " ";
}
}
Clarification from comments
I would like the Form to Change the color on close after the button is clicked. This is what I tried:
private void btnRed_Click(object sender, EventArgs e)
{
Color c = Color.Red;
string s = c.ToString();
this.Close();
}
To answer your question, create a property on your Color Form that is set by your button you can then read it after the Form is closed when it returns from your ShowDialog statement.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
if(frm2.ShowDialog() == DialogResult.OK)
{
//this.BackColor=frm2.getColor; helps if I read the question more closely
richTextBox1.SelectionColor = frm2.getColor;
}
}
}
Form2
public partial class Form2 : Form
{
public Color getColor { get; set; }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
getColor = Color.Red;
DialogResult = DialogResult.OK;
}
}
After playing with the code that you posted and added some missing handlers, it looks like the text of your color is coming in the Format of Color [Red] ColorFromName has no idea how to parse that so you will need to get the actual color name by using String.Split Something like this.
protected void ColorWindow_myEventHandler(object sender, SecondWindowEventArgs e)
{
rtf2.ForeColor = Color.FromName(e.S.Split(new string[]{"[","]"},StringSplitOptions.None)[1]);
}
I also noticed that you are setting your rtf2.ForeColor everytime that your text changes, I removed it and am now able to change the ForeColor of the RichText box. I would be a lot easier/cleaner IMHO if you just passed the actual Color Object instead of changing it to a string and back.
This is the modified TextChanged Method note the commented out rtf2.ForeColor statement it does not belong there.
private void rtf2_TextChanged(object sender, EventArgs e)
{
if (myEventHandler != null)
{
myEventHandler(this, new FirstWindowEventArgs(rtf2.Text.Substring(rtf2.Text.Length -1)));
// rtf2.ForeColor = Color.FromName(e.ToString());
}
}

Movable UserControl in WPF

I created simple UserControl with several labels. How can I implement simple mechanism, that allows moving whole control like normal window (when I add it to winForms - if it makes difference)
You can use my Capture class:
public class ClsCapture
{
bool bCaptureMe;
Point pLocation = new Point();
Control dd;
//Handles dad.MouseDown, dd.MouseDown
private void Form1_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try {
bCaptureMe = true;
pLocation = e.GetPosition(sender);
} catch {
}
}
//Handles dad.MouseMove, dd.MouseMove
private void Form1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
try {
if (bCaptureMe) {
dd.Margin = new Thickness(dd.Margin.Left - pLocation.X + e.GetPosition(sender).X, dd.Margin.Top - pLocation.Y + e.GetPosition(sender).Y, dd.Margin.Right, dd.Margin.Bottom);
}
} catch {
}
}
//Handles dad.MouseUp, dd.MouseUp
private void Form1_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try {
bCaptureMe = false;
} catch {
}
}
public ClsCapture(Control pnl)
{
dd = pnl;
dd.PreviewMouseLeftButtonDown += Form1_MouseDown;
dd.PreviewMouseLeftButtonUp += Form1_MouseUp;
dd.PreviewMouseMove += Form1_MouseMove;
}
public static void CaptureMe(Control pnl)
{
ClsCapture cc = new ClsCapture(pnl);
}
}
Usage:
ClsCapture.CaptureMe(AnyControlYouWant);

Categories