How can I add a splash screen to my C# application? [duplicate] - c#

How can we show startup picture when my application starts as every software hows like Photoshop ,vs word etc?? I planed to paste it on form and then show it but there is top blue bar coming that has controls etc any idea/

If you're looking for the simplest way, you can use the .NET Framework's excellent built-in support for splash screens. You'll have to put aside any irrational fears that you might have of including something with the name "Visual Basic" in a C# application, but this way will save you from having to roll your own custom solution and worry about things like multi-threading, invoking, and all that. It all compiles down to the same IL in the end anyway. Here's how it works:
Add a reference to Microsoft.VisualBasic to your project.
Add a new form (named something like SplashForm) to serve as your splash screen.
To make it look more like a proper splash screen, set the form's FormBorderStyle property to "None" and its StartPosition property to "CenterScreen". You can add any controls or images to this form that you want to be displayed on the splash screen to this form.
Add the following code to your Project.cs file:
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new SplashScreenApp().Run(args);
}
}
public class SplashScreenApp : WindowsFormsApplicationBase
{
protected override void OnCreateSplashScreen()
{
this.SplashScreen = new SplashForm();
this.SplashScreen.ShowInTaskbar = false;
this.SplashScreen.Cursor = Cursors.AppStarting;
}
protected override void OnCreateMainForm()
{
//Perform any tasks you want before your application starts
//FOR TESTING PURPOSES ONLY (remove once you've added your code)
System.Threading.Thread.Sleep(2000);
//Set the main form to a new instance of your form
//(this will automatically close the splash screen)
this.MainForm = new Form1();
}
}
}
If you want to do something fancy like create a transparent splash screen in the style of Adobe Photoshop, you can add an alpha-channel PNG image to your project's Resources file, and then add the following code to your splash screen form, replacing splashImage with the path to your embedded image resource:
protected override void OnPaintBackground(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.DrawImage(splashImage, new Rectangle(0, 0, this.Width, this.Height));
}
protected override void OnPaint(PaintEventArgs e)
{
//Do nothing here
}
For this to work, make sure that you have double buffering turned off, or else you'll get a black background to your form. There's really no reason to double buffer a splash screen anyway.

You can remove all those blue bars etc, via this.FormBorderStyle = FormBorderStyle.None in your Form_Load().
So if I were you, I'd create a Form of specific Size, then set the following in Form_Load()
or directly in the code generated by the designer:
this.FormBorderStyle = FormBorderStyle.None;
this.StartPosition = FormStartPostition.CenterScreen;
Now you have a splash screen like many other apps - all you have to still do is write the code for all the making it visible or not stuff etc :)

WPF 3.5 and above actually has built in splash screen support, for faster rendering of the splash screen and much (much) less faffing with code. See this page for details.

Are you writing a WinForms or a WPF application? You will have to set different properties depending on which kind you write. If you are writing a WPF application, you can add the WindowStyle="None" and ResizeMode="NoResize" attributes to the Window top-level element in XAML. The first one will remove the title bar with the minimize, resize, and close buttons whereas the second one will remove the border around the form.
Now, you have a borderless form that you can modify to create a splash screen if you want or to simply add your startup image. If you don't want your default form to appear, you need to add Background="Transparent" and AllowsTransparency="True" attributes as well. The first one will set the background color to transparent whereas the second one allows your program to look transparent. Now, you can add any image in any shape, and the user will see only that image at program startup.
P.S. Make sure to load another form once the startup screen has been shown for a set amount of time or once the methods that are supposed to "load" stuff return control.
Pretty simple stuff!!

Related

CefSharp WinForms - Flickering when page loading

I am using CefSharp.WinForms version 84.4.10.
My application is a wip game launcher for the games I make.
Screenshot of the launcher.
There is a Main form that loads and unloads child forms when buttons are pressed. The child forms contain a panel stretched to fill the whole child form. The CefSharp is initialized on the panel.
Here's the code that does that:
public CefSharp.WinForms.ChromiumWebBrowser browser;
private void Changelog_Load(object sender, EventArgs e)
{
browser = new CefSharp.WinForms.ChromiumWebBrowser("https://aerial-knightstudios.com/store/akslauncher/")
{
Dock = DockStyle.Fill,
Size = new Size(600, 600),
Location = new Point(200, 200),
};
this.panelChangelogPage.Controls.Add(browser);
}
When the child form is enabled, a black box appears that fills half the form then it flickers white then the webpage loads.
So far I have tried the following:
I have turned on double buffering by adding DoubleBuffered = true; inside public FormMain() and this made the flickering less intense, but it still flickers a lot.
I also changed [STAThread] in program.cs to [MTAThread]. This also helped, but very slightly.
Any solutions are welcome.

How can I add transparency to a c# form while keeping controls visible?

UPDATE: I took a break from messing with the transparency stuff for a few days. I started messing with it again tonight. I got a new result using Hans Passant's solution:
http://img3.imageshack.us/img3/4265/icontransp.jpg
Passant's solution does solve the issue of the transparent background gradient. However, I'm still running into the problem with the transparent colors in my icon blending with the form's BackColor. You can see the fuchsia around various parts of the icon in the above image.
ORIGINAL CONTENT:
I've been going at this for several hours now, and I haven't had much luck. I've messed with Control.Region, Form.TransparencyKey, Form.Opacity, and a couple other random things with some funky effects.
Lately I've been trying to customize my desktop and decided to mess with Application Docks. After seeing what the Mac dock and a few third-party Windows implementations had to offer, I decided I wanted to build my own.
Eventually I want to move on to using the Win32 API. For now I just want to get something working using as much C# and .Net framework capabilities as possible.
There are a few things I want to be able to do in this application:
Display a form/menu with a gradient background.
Allow the form/menu to have transparency while keeping icons opaque.
Display icons that contain transparent backgrounds.
The Menu and Icons should be able to receive mouse-related events (hover, leave, click, dragover, dragdrop, and a few others).
This is the effect I'm shooting for:
http://img207.imageshack.us/img207/5716/desired.jpg
This image shows the visual effects I'm trying to achieve. This was a skin I made for a program called Rainmeter. The image shows Notepad++ behind the skin with a few of the skin's files open in the editor. The menu is transparent, but the icons remain opaque.
My Approach:
Using a Form to act as the menu seemed like a logical first choice to me. I have a basic understanding of events. I'm not quite sure how to create my own click events, so a form would make working with events a tad easier. I considered a few options for the icons. I decided I'd use PictureBoxes for the icons, since they can hold images and receive events.
Once I finished the code for all the structural logic of my menu, I started playing around with it to try to get the visual effect I wanted. Form.Opacity affected the transparency of everything on the form. Since I want the icons to be fully opaque, I left this property alone. I tried setting the BackColor to Color.Transparent, but that gives an error. I played around with a few combinations...
http://img204.imageshack.us/img204/757/effectsi.jpg
I drew the gradient with a Drawing2D.LinearGradientBrush into a Bitmap. This Bitmap was then placed as the Form.BackgroundImage or as a PictureBox.Image. If used, the PictureBox was sized to cover the entire Form and sent to the back.
I noticed that some of the Form.BackgroundColor would be mixed in with the outlines of my icons. The icons have transparency along the edges for a smoother appearance. Since the icons are picking up the Form's BackgroundColor, this makes me think that the PictureBoxes are creating new images when the icons are loaded into the form. The semi-transparent portions of the image are then merged with the Form's BackgroundColor when they should merge with whatever colors are behind the form.
http://img838.imageshack.us/img838/8299/whitedesktop.jpg
In this image you can see the Fuchsia existing in the icons even though the Form's Fuchsia color is now completely transparent. I forgot to point out that the same green to yellow gradient with an Alpha value of 150 was used in every case. In the images where the gradient doesn't look green, it's because the transparent colors are blending with the Fuchsia background.
I'm not really sure what to do from here. I feel like I could get what I want if I could somehow make the Form alone completely transparent. I was also thinking I may have better luck just drawing the icons instead of using PictureBoxes. The problem then would be setting up the icons to receive mouse events. (I've never made my own events, and I think it would involved some Win32 API calls.)
Is there something else I can do with the PictureBoxes to get the effect I want? Whichever the case, I'm open to any ideas or suggestions for the overall effect I'm trying to achieve.
This is pretty easy to do in Winforms. What you need is a sandwich of two forms. The bottom one should provide the transparent gradient background, the top one should draw the icons and handle mouse clicks. Some sample code:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.TransparencyKey = this.BackColor = Color.Fuchsia;
this.Opacity = 0.3;
var overlay = new Form();
overlay.FormBorderStyle = FormBorderStyle.None;
overlay.TransparencyKey = overlay.BackColor = Color.Fuchsia;
overlay.StartPosition = FormStartPosition.Manual;
overlay.Location = this.Location;
overlay.MouseDown += HandleIconClick;
this.Resize += delegate { overlay.Size = this.Size; };
this.LocationChanged += delegate { overlay.Location = this.Location; };
overlay.Paint += PaintIcons;
this.Paint += PaintBackground;
this.Load += delegate { overlay.Show(this); };
}
private void PaintBackground(object sender, PaintEventArgs e) {
var rc = new Rectangle(0, 0, this.ClientSize.Width, this.ClientSize.Height);
using (var br = new LinearGradientBrush(rc, Color.Gainsboro, Color.Yellow, 0f)) {
e.Graphics.FillRectangle(br, rc);
}
}
private void PaintIcons(object sender, PaintEventArgs e) {
e.Graphics.DrawIcon(Properties.Resources.ExampleIcon1, 50, 30);
// etc...
}
void HandleIconClick(object sender, MouseEventArgs e) {
// TODO
}
}
Which looks like this with the somewhat random colors and icon I selected:
OK, I got a bit lost in all that, but from the description in the original paragraph, I would make sure the background rectangle is NOT the visual parent of the pictureboxes. Make them overlapping siblings, with the pictureboxes in front using Panel.Zindex.
Then you can just change the opacity of the rectangle, without affecting the icons. Also make sure the icon source image files have a transparent background.
Should work I think.

Drawing an image onto a Panel control gives artefacts when resizing

Currently I'm trying to do what I thought would be a simple task:
Draw an image onto the full area of a Panel control in Windows Forms. (Please ignore for the moment that I could use the BackgroundImage property)
The image to draw looks like this:
I.e. a yellow box with an 1 pixel blue frame around.
To draw, I'm using the Paint event of the Panel control:
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(Resources.MyImage, panel1.ClientRectangle);
}
This looks fine when initially displaying the form:
When resizing the form (and the docked panel, too), it either cuts the edges when being made smaller...
...or it draws artefacts, when being made larger:
I'm pretty sure that there is going on something rather simple and straight-forward but I really cannot understand the reason.
Since I'm ignoring the ClipRectangle and always draw everything, I thought the image would be scaled all the time.
My questions are:
What is the reason for the artefacts? (I love to understand this!)
What do I have to do in order to get rid of the artefacts? (beside calling Invalidate on each resize)
Update, SOLUTION:
Thanks to Ryan's answer, I was able to find an acceptable solution. Basically I derived a class from Panel, did an override of OnPaintBackground and did not call the base method. Last, I added the following code to the constructor of my derived panel:
base.DoubleBuffered = true;
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();
The reason for the artefacts is that the entire surface isn't redrawn when the form is resized; only the necessary parts are. The generally best solution is what you don't want to do, calling Invalidate on each resize. However, if this is in fact your situation, just use a PictureBox instead. If it's not, you might consider overriding OnPaint in your form instead, and using this.SetStyle(ControlStyles.ResizeRedraw, true) to do this automatically.

How to dock a windows form in C#?

I just would like to know if it is possible to dock a windows form on top of the user screen? I have been trying to do this by manually setting the position of my form to the coordinates I want. But using this method, however, allows the user to change the position of the form just by dragging it. I want to make the form docked to the upper portion of the screen since this window form will server as a menu for the project I am making.
Thanks a lot. :)
I would consider using the Control.Dock property along with one of the DockStyle enumeration values.
You might need to play with the Layout too, so that you may layout your form's controls differently depending on the DockStyle selected.
You will need, in my point of view, to consider the Control.Location property so that you get to know which DockStyle value to dock your form with.
EDIT #1
Your Windows Form has a Dock property as it inherits from Control.
Let's consider the following :
Each time your form comes closer to your right-side of the screen, for example, or of the MDI container, you want to dock right, right ? (Little word play here... =P) So, you have to subscribe to the Control.LocationChanged event.
private void myForm_LocationChanged(object sender, EventArgs e) {
if (this.Location.X > 900) then
this.Dock = DockStyle.Right;
else if (this.Location.X < 150) then
this.Dock = DockStyle.Left;
else if (this.Location.Y > 600) then
this.Dock = DockStyle.Bottom;
else if (this.Location.Y < 150) then
this.Dock = DockStyle.Top;
else
this.Dock = DockStyle.None;
}
Indeed, instead of constant values, you should use the current desktop resolution and calculate a ratio from it where you want your docking to occur.
***Disclaimer:****This code is provided as-is and has not been tested. This algorithm is hopefully enough to guide you through the docking process as you need it. Further assistance may be brought upon request.* =)
It seems the Form.DesktopLocation property is the righter tool for the job as for your main window, meaning your MDI container, for instance. As for the other windows, I would go along with something that looks like the code sample provided.
Does this help?
EDIT #2
If you want to prevent Form's overlapping, perhaps the Control.BringToFront() method could do it before or after your call to the Control.Show() method, depending on what works best for you.
So after some tweaks I finally was able to get this code working.
this.DesktopLocation = new Point((Screen.PrimaryScreen.Bounds.Width / 2 - 420), 0);
I placed that line below the InitializeComponent() and it docks my form to the center of the screen with whatever resolution values.
By setting the FormBorderStyle of your form to None, you take the drag handle away from the user so they cannot move it via the mouse.
Then you just need to place it where you want.
If you really want to take away the users options you can also set the ShowInTaskbar property to false

Gradient Drawing Bug

I'm having trouble with a gradient drawing call. I have a Form that looks like this.
Screenshot http://img413.imageshack.us/img413/3570/30364682.png
The problem is every now and again the above gradient drawing bug will start happening. It should go right across of course. Sometimes it only takes some build-rebuild-mashing to fix and it'll simply just "start" after a build every now and again.
That control (the top white part) is a TableLayoutPanel. The BackColor is set to white and on the panel's Paint event I do this:
/// <summary>
/// Draws the background gradient.
/// </summary>
private void titleBarLayoutPanel_Paint(object sender, PaintEventArgs e)
{
Brush brush = new LinearGradientBrush(titleBarLayoutPanel.Bounds, TaskHeaderLeftColor, TaskHeaderRightColor, LinearGradientMode.Horizontal);
e.Graphics.FillRectangle(brush, titleBarLayoutPanel.Bounds);
}
Should I be doing something else? The problem is that it works, and then without so much as a rebuild or build this will start happening!
EDIT I have since rebuilt the class library it is contained in (it's a generic Form) then rebuilt the app it's used in and the gradient is now filling across completely. This is bizarre.
Building and re-building your application, with no changes, normally doesn't solve this (or most any other bug for that matter) save the ones in which you run your application without doing a clean/rebuild first and then notice that the code you just wrote doesn't run (not sure that's possible these days with the IDEs). I see this a lot with newer devs when they keep rebuilding hoping that somehow the compiler will make the code "correct" or that maybe the compiler is simply not generating the correct code to begin with. (Please note that I do not mean the aforementioned statements to be taken disparagingly.)
To solve the issue at hand, you might try deriving your own TableLayoutPanel class in which you override the OnBackgroundPaint event, painting your own background, or simply returning if you don't want to paint your own background. (You seem to be painting the background in the Paint event). What you are doing in the code above is simply painting over the background already painted by the control, hence the "bug" you see, (double paint). It appears that the form is not resizable. Try making it resizable. Then resize it and watch it paint, or simply move other windows over it.
class CustomTableLayoutPanel : TableLayoutPanel
{
protected override void OnPaintBackground(PaintEventArgs e)
{
Brush brush = new LinearGradientBrush(this.ClientRectangle, TaskHeaderLeftColor, TaskHeaderRightColor, LinearGradientMode.Horizontal);
e.Graphics.FillRectangle(brush, this.ClientRectangle);
//base.OnPaintBackground(e);
}
}
By the way, you should replace Bounds with ClientRectangle.
Bounds is the control's rectangle relative to its parent; ClientRectangle is relative to the control itself.
In this particular case, it won't make a difference, since the control is at 0, 0.

Categories