Си шарп рандомный цвет

How to generate random color codes in c# .net?

In this article I will show you to generate random color codes in c# .net implemented to display data with different color variation for chart.

Color randomColor = Color.FromKnownColor(randomColorName);

You need to include assembly reference using System.Drawing . You will get the generated color code like randomColor.Name.

var colorcode = randomColor.Name;
private string getRandColor()

Random rnd = new Random();
string hexOutput = String.Format("", rnd.Next(0, 0xFFFFFF));
while (hexOutput.Length < 6)
hexOutput = "0" + hexOutput;
return "#" + hexOutput;
>
var colorcode = getRandColor(); 

Источник

Рандомный выбор цвета

Смена цвета карандаша после каждой итерации на рандомный
Как изменить после каждой итерации цвет карандаша на рандомный? for (int i = 0; i < 50;.

Рандомный выбор числа из диапазона
Используется: С# Как сделать чтобы рандомизация осуществлялась по двум вариантам? Вариант 1.

Изменение цвета названия файла/папки (либо цвета подсветки)
Привет супер уважаемые супер форумчане!) Очень интересно, есть ли какой-то способ изменить цвет.

ContextMenu изменение цвета выбора и цвета текста
Добрый день подскажите как сделать так что бы после выбора пункта меню цвет текста менялся обратно.

Эксперт Java

Генерируете 3 случайных числа от 0 до 255, после чего создаете Color, в соответствии со сгенерированными числами (R,G,B).
Потом выставляете полученный цвет для кнопки.

Лучший ответ

Сообщение было отмечено CyberAlfred как решение

Решение

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
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 new_changecolor { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { while(Visible) { for (int p = 0; p  255 && Visible; p++) { this.BackColor = Color.FromArgb(p, 255 - p, p); Application.DoEvents(); System.Threading.Thread.Sleep(4); } for (int c = 254; c > 0 && Visible; c--) { this.BackColor = Color.FromArgb(c, 255 - c, c); Application.DoEvents(); System.Threading.Thread.Sleep(4); } } } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace orum { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Random random = new Random(); this.BackColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)); } } }

Источник

Си шарп рандомный цвет

Gray Pipe

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

Hello How can i get random color for my reports and the imp thing that the color combination must be readable. Thanks Shival Thakur

Answers

You’ll have to compose a LIST of background color and text color on your own. Then, pick a random number that is within the number of items in the list, and pick one of the patterns.

public partial class Form1 : Form < ListcolorCombinations = new List()< new ColorCombination< BackgroundColor="Red", TextColor="Gray">, new ColorCombination< BackgroundColor = "Yellow", TextColor = "Brown">, new ColorCombination< BackgroundColor = "Pink", TextColor = "Red">>; Random rnd = new Random(); public Form1() < InitializeComponent(); >private void Form1_Load(object sender, EventArgs e) < // Pick a random color int c = rnd.Next(0, colorCombinations.Count); // Use it this.BackColor = Color.FromName(colorCombinations[c].BackgroundColor); this.ForeColor = Color.FromName(colorCombinations[c].TextColor); > > // CLASS FOR COLOR COMBINATIONS class ColorCombination < public string BackgroundColor; public string TextColor; >

Noam B. Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you.

  • Proposed as answer by Marcus Pålsson Monday, October 10, 2011 12:34 PM
  • Marked as answer by Bob Wu-MT Wednesday, October 19, 2011 2:34 AM

Источник

Си шарп рандомный цвет

Gray Pipe

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I am a beginner in C# and need to generate a random background color every time a Window2 is initiated. Any help here? I have a method that looks like this.

private void Window_Loaded(object sender, RoutedEventArgs e)

I already have a Window1 that has a button. When clicked the button opens this Window2.
So when the Window2 is loaded I need a random background color. Please help! I know it should be easy, but i’ve only been doing this for about one month. Thanks!

Answers

MSearles already provided a good post for you. The key point in this case is to call the Random.Next method to generate different color for the window’s background. In the below example, I utilize Color.FromRgb method to generate different R,G,B values randomly.

Code snippet:
private void OnShowWindow2(object sender, RoutedEventArgs e)
Window window2 = new Window();
Random random = new Random();
SolidColorBrush brush =
new SolidColorBrush(
Color.FromRgb(
(byte)random.Next(255),
(byte)random.Next (255),
(byte)random.Next (255)
));
window2.Background = brush;
window2.Show();
>

If you are still having any issues with this case, please feel free to let me know.
Thanks.
Sincerely. Jim Zhou -MSFT

  • Proposed as answer by Olaf Rabbachin Saturday, March 6, 2010 11:30 AM
  • Marked as answer by Jim Zhou — MSFT Monday, March 8, 2010 1:32 PM

Источник

Как создать случайный цвет?

Как создать палитру цветов и как узнать выбранный цвет
Подскажите как можно реализовать такую задачу, пользователь выбирает палитру цветов, после выбора.

Как поменять цвет текста консоли на любой цвет из RGB цветов
Цвет консоли можно поменять используя только 16 встроенных цветов или можно использовать комбинации.

Как отсортировать случайный столбец?
Например задана матрица, размеры которой вводятся пользователем и надо случайный столбец матрицы.

Как сделать случайный переход на одну из диапазона страниц
Подскажите, пожалуйста, как сделать случайный переход на одну из диапазона страниц.

Color c = Color.FromArgb(r.Next(256), r.Next(256), r.Next(256));

Эксперт .NET

ЦитатаСообщение от craftersmine Посмотреть сообщение

Как задать случайный цвет фигуре
Надо чтобы фигура меняла цвет(рандомно) по таймеру Dim R As Integer, G As Integer, B As Integer.

случайный цвет
суть задания такова:нарисовать прямоугольник,который бы менял свой размер и цвет(не по таймеру,а.

Случайный цвет
Как сделать случайный выбор цвета. То есть что то типа этого но лучше. x=rand() % 5; if (x==0).

Выбрать случайный цвет
У меня есть 6 radio-элементов, пользователь может выбрать одно из этих значений. <p>Choose the.

Источник

Читайте также:  How to enable javascript in your web browser
Оцените статью