0 / 0 / 0 Регистрация: 13.12.2012 Сообщений: 25 |
|
1 |
|
19.12.2012, 22:54. Показов 20767. Ответов 15
Доброго здоровица. Помогите пожалуйста. Суть такая, я в этом новый человек и только учусь. Взялся делать дипломную работу (из области судовождения). Делаю несколько влкдок через элемент tabControl, в одной вкладке я меня цвет всей формы, но поверх самой формы находится tabControl, и получается, что цвет не меняется. А суть работы состоит в том, что создаю программу по расхождению с целями (судами), где главное окно (будет вкладка) — это как бы локатор, куда я забиваю координаты самой цели (направление и расстояние), и потом программа рекомендует маневр, но с этим я потом в дальнейшем буду разбираться. Вообщем думаю интересно это все и пока вникаю. Спасибо.
__________________
0 |
0 / 0 / 0 Регистрация: 13.12.2012 Сообщений: 25 |
|
22.12.2012, 15:58 [ТС] |
2 |
Наверно я некорректно поставил вопрос либо задачу)
0 |
1448 / 1120 / 345 Регистрация: 11.04.2011 Сообщений: 2,615 |
|
22.12.2012, 18:55 |
3 |
Действительно, из того, что вы написали, очень сложно понять, чего вы хотите. Попробую наугад. У любого класса, унаследованного от класса Control, есть свойство Background, при помощи которого можно менять цвет фона контрола. Как сам TabControl, так и каждая его вкладка имеют это свойство.
1 |
Mindhunter 0 / 0 / 0 Регистрация: 13.12.2012 Сообщений: 25 |
||||
22.12.2012, 22:05 [ТС] |
4 |
|||
Вобщем я как делаю. Создал TabControl, в одной из влкадок создал несколько кнопок, каждая кнопка меняет цвет фона всей программы, но у меня меня только задний план. Просто не получается сделать так, чтобы этот самый tabControl был с главной формой одно целое. Добавлено через 34 минуты
0 |
kodv 1448 / 1120 / 345 Регистрация: 11.04.2011 Сообщений: 2,615 |
||||
23.12.2012, 05:42 |
5 |
|||
Для начала попробуйте добавить к форме обработчик события BackColorChanged:
Здесь при зименении заднего фона окна мы меняем цвет заднего фона таб контрола. Если потребуется, прийдется с таб пейджом сделать то же самое. Нет сейчас C# под рукой, не могу поэкспеременитровать самостоятельно.
1 |
0 / 0 / 0 Регистрация: 13.12.2012 Сообщений: 25 |
|
23.12.2012, 07:53 [ТС] |
6 |
А куда добавить? А то пишет, что tabControl не существует в текущем контексте. В разные места прописывал уже.
0 |
1448 / 1120 / 345 Регистрация: 11.04.2011 Сообщений: 2,615 |
|
23.12.2012, 09:29 |
7 |
Вообще — это событие, которое возникает при изменении свойство BackColor у вашей формы. То есть выбираете в дизайнере форму, в свойствах открываете вкладку событий, ищите там событие BackColorChanged, жмете на нем 2 раза, и пишете в нем тот код, который я привел.
1 |
0 / 0 / 0 Регистрация: 13.12.2012 Сообщений: 25 |
|
23.12.2012, 19:17 [ТС] |
8 |
Че то не получается. Пробовал так, просто не срабатывает, потом еще пробовал в разные места прописывать. Ошибок нету, но так же цвет меняется за окном которые надо (т.е. в форме, а она получается за всей этой tabcontrol)
0 |
Почетный модератор 21367 / 9101 / 1082 Регистрация: 11.04.2010 Сообщений: 11,014 |
|
23.12.2012, 20:02 |
9 |
kodv, Mindhunter, зачем вы целиком цитируете друг друга? Кроме вас тут больше нет никого, и так понятно, с кем вы разговариваете. Замечание.
1 |
kodv 1448 / 1120 / 345 Регистрация: 11.04.2011 Сообщений: 2,615 |
||||
24.12.2012, 08:53 |
10 |
|||
Говорю же, у TabPage тоже есть такое свойство. Тогда попробуйте так:
1 |
0 / 0 / 0 Регистрация: 13.12.2012 Сообщений: 25 |
|
24.12.2012, 20:11 [ТС] |
11 |
Спасибо большое за помощь, чуть другим путем пошел, посложнее. Но пока так.
0 |
2 / 2 / 0 Регистрация: 02.11.2013 Сообщений: 27 |
|
15.11.2015, 13:33 |
12 |
Что то я не понял. У TabControl нет свойства BackColor, оно есть только в его вкладках (TabPage).
0 |
6 / 5 / 3 Регистрация: 04.06.2015 Сообщений: 250 Записей в блоге: 1 |
|
17.03.2017, 16:41 |
13 |
Товарищи! Смежный вопрос по теме. Добавлено через 10 минут
0 |
6 / 5 / 3 Регистрация: 04.06.2015 Сообщений: 250 Записей в блоге: 1 |
|
21.03.2017, 16:31 |
15 |
Спасибо, предложенный вариант интересный, но делает не совсем то, что мне нужно. Попробовал проделать так же. Да, получилось, но результат — фон вокруг табпейджа стал прозрачным, а мне же нужно, чтоб при свойстве самого контрола свойстве Appearence = FlatBattons (верхушки вкладок становятся в виде кнопок), фон полоски, на которой расположены эти верхушки вкладок в виде кнопок, был прозрачным. Вот при свойстве Appearence = Normal эта полоска как раз таки прозрачная (правда если там еще одно свойство изменить, не помню какое именно), но почему-то при тех же настройках с Appearence = FlatBattons, эта полоска быть такой же прозрачной не хочет. Добавлено через 1 час 32 минуты
0 |
8 / 8 / 2 Регистрация: 30.01.2015 Сообщений: 157 |
|
24.02.2018, 10:42 |
16 |
Ребята подскажите, как сделать вот такую вещь. У меня есть TabControl, у него две вкладки (TabPage). Содержимое на самих вкладках (TabPage) одинаковое, различие только в заголовке вкладки, ну например, вкладка «Зима» и «Осень». И когда кликаю по вкладкам, то цвет заголовка вкладки меняется, становится немного светлее, но это не очень заметно, можно ли сделать так, что при клике на вкладку, именно заголовок вкладки становился красным или каким то другим цветом, чтоб четко было видно какая вкладка выбрана. Заранее спасибо!
0 |
First of all you need to make a deriving class from TabControl. So far so good but now it gets dirty.
Because TabControl won’t call OnPaint
, we have do override WndProc
to handle the WM_PAINT message. In there we go ahead and paint our background with the color we like.
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if(m.Msg == (int) WindowsMessages.Win32Messages.WM_PAINT)
{
using (Graphics g = this.CreateGraphics())
{
//Double buffering stuff...
BufferedGraphicsContext currentContext;
BufferedGraphics myBuffer;
currentContext = BufferedGraphicsManager.Current;
myBuffer = currentContext.Allocate(g,
this.ClientRectangle);
Rectangle r = ClientRectangle;
//Painting background
if(Enabled)
myBuffer.Graphics.FillRectangle(new SolidBrush(_backColor), r);
else
myBuffer.Graphics.FillRectangle(Brushes.LightGray, r);
//Painting border
r.Height = this.DisplayRectangle.Height +1; //Using display rectangle hight because it excludes the tab headers already
r.Y = this.DisplayRectangle.Y - 1; //Same for Y coordinate
r.Width -= 5;
r.X += 1;
if(Enabled)
myBuffer.Graphics.DrawRectangle(new Pen(Color.FromArgb(255, 133, 158, 191), 1), r);
else
myBuffer.Graphics.DrawRectangle(Pens.DarkGray, r);
myBuffer.Render();
myBuffer.Dispose();
//Actual painting of items after Background was painted
foreach (int index in ItemArgs.Keys)
{
CustomDrawItem(ItemArgs[index]);
}
}
}
}
Im doing further drawing in this method so it looks a little overkill for this problem but just ignore the unnecessary stuff.
Also notice the foreach
loop. I’ll come to this later.
The Problem is that TabControl
paints its items (the tab headers) before its own WM_PAINT so our background will be drawn on top, which renders them invisible. To solve this I made an EventHandler
for DrawItem
which looks as the following:
private void DrawItemHandler(object sender, DrawItemEventArgs e)
{
//Save information about item in dictionary but dont do actual drawing
if (!ItemArgs.ContainsKey(e.Index))
ItemArgs.Add(e.Index, e);
else
ItemArgs[e.Index] = e;
}
I am saving the DrawItemEventArgs
into a dictionary (which is called «ItemArgs» in my case) so I can access them later. Thats where the foreach
from a few seconds ago comes into play. It calls a method where I am painting the tab headers which takes the DrawItemEventArgs
which we saved before as a parameter to paint the items in correct state and position.
So, in a nutshell we are intercepting the Drawing of tab headers to delay it until we are finished drawing the background.
This solution is not optimal but it works and its the only thing you can do to get more control over TabControl
(lol) without painting it from scratch.
- Download source — 13 Kb
Introduction
Tabcontrol is not at all unknown to windows developers. Microsoft included
this control from Visual Studio to Visual Studio.NET SDK to enhance developers
productivity and end users better experience. I agree that our windows
development must flow some standard to give better user experience. Here I am
trying to give little more enhancement on control appearance if and only if
developer want to do it.
Background
This article is small in size and can apply in your different application
only if it must be a winform development. You can refer this article to update
your tab control’s appearances in your parent window.
By default or through any properties the existing VS.NET SDK won’t support
features which will enhance the appearances of tab pages like changing font
appearances , color,caption back color etc. Here what I am trying to do is ,
override a little and got into solution. So you can use this idea to enhance
your product or project.
If you feel this is good then don’t forget to vote and give put your
valuable suggestions.
If you check the property list of tabcontrol. You will came to to about
DrawMode
property. DrawMode
property decides that how
tabpages are drawn in your application. If you check the values then you will
came to that there is two values are there which is assignable for the property
DrawMode
.
DrawMode
Enumeration
Normal
This enumerated value will specify that operating system will decide to draw
on behalf of developers.
OwnerDrawn
This enumerated value will specify that developer is responsible for drawing
the appearance of tab page.
Suppose if you want to draw by yourself then you need to define event handler
for TabControl’s DrawItem
Event.
Here also I am doing the same thing. Suppose it you want to change the
appearance of tabpage of any tabcontrol then you need to set
DrawMode
property toOwnerDrawFixed
.- Override the
DrawItem
event handler definition.
Source Code
private void tabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { try { Font f; Brush backBrush; Brush foreBrush; if(e.Index == this.tabControl1.SelectedIndex) { f = new Font(e.Font, FontStyle.Bold | FontStyle.Bold); f = new Font(e.Font,FontStyle.Bold); backBrush = new System.Drawing.SolidBrush(Color.DarkGray); foreBrush = Brushes.White; } else { f = e.Font; backBrush = new SolidBrush(e.BackColor); foreBrush = new SolidBrush(e.ForeColor); } string tabName = this.tabControl1.TabPages[e.Index].Text; StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; } }
Note
Full source code with an example is given with this article.
He is a certified professional in both MCPD and MCTS. He is a mathematics graduate with masters in computer science.He was born and bred in India and happen to spend some time in Europe.