I want to make a C# Windows Forms App That displays a pen which changes into a pineapple when you click it, turns into an apple when you click the pineapple and the back into a pen, which, when you click, starts a music video.
What doesn't work for me is the video, which I do not want to display in a Windows Media Player plainly because I don't like it. Here is the 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;
using Microsoft.DirectX.DirectSound;
using Microsoft.DirectX.AudioVideoPlayback;
using Microsoft.DirectX;
namespace Picture_Button
{
public partial class Form1 : Form
{
Video video = new Video("C:\\Users\\Pushkin\\Desktop\\PPAP.mp4");
private int clicks = 0;
public Form1()
{
InitializeComponent();
video.Owner = this;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
clicks++;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
switch (clicks)
{
case 0: pictureBox1.Image = Properties.Resources.Pineapple; break;
case 1: pictureBox1.Image = Properties.Resources.Apple; break;
case 2: pictureBox1.Image = Properties.Resources.Pen; break;
case 3: video.Play(); break;
case 4: video.Dispose(); break;
}
}
}
}
And literally nothing happens, the program simply freezes as if it were into an infinite loop here:
Video video = new Video("C:\\Users\\Pushkin\\Desktop\\PPAP.mp4");
Nothing shows up. Any ideas what the problem is?
EDIT: I'm trying to handle the Ending event so I can make the app exit when the video ends and somehow I managed to get this exception:
System.NullReferenceException occurred
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Microsoft.DirectX.AudioVideoPlayback
StackTrace:
at VideoWndProc(HWND__* hWnd, UInt32 uMsg, UInt32 wParam, Int32 lParam)
InnerException:
By adding this code:
video.Ending += new System.EventHandler(this.Video_Ending);
//some code
private void Video_Ending(object sender, EventArgs e)
{
//throw new NotImplementedException();
video.Dispose();
Application.Exit();
}
There are two separate issues here:
Support for Legacy .net
First issue: "DirectX for Managed Code" is very old and based on .net version 1.1. In order to use this assembly in .net 4 or newer, you need to enable loading these older formats. You do this by changing the file "app.config" in your project and setting useLegacyV2RuntimeActivationPolicy to true on the startup node, so it looks similar to this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true" >
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
Note that during debugging, you can get an exception "Managed Debugging Assistant 'LoaderLock' has detected a problem". You can ignore this exception. Tell Visual Studio that it should not stop at this exception during debugging.
Related question/answer
Codec support
The second issue is that you need to have a codec installed that allows DirectX to play mp4 files.
These codecs are not included by default in most versions of Windows (also not in Windows 10). Even when your Windows Media Player can playback an mp4 file, this doesn't mean the correct codec is available that can be used from DirectX.
I found that installing the LAV filters is a simple and non-intrusive way of making most video formats available to DirectX on Windows.
Video Playback in Debug Mode
You will find that often when you start the application from Visual Studio, video playback will be choppy and have a low quality. Quality will be perfect when starting the application without debugging.
Related
I want to create simple toast notification to action center in windows 10 from this example. But I got problem on Step 2:
using Windows.UI.Notifications;
It`s missing. But I have spent a lot of time to find it and got no result. I really have no idea where I can find or at least download it.
What I tried:
After long search I found Windows.UI.dll in C:\Windows\System32 but when I try to add it as reference into project I got this error. Even after I tried to copy it and made this fully accessible nothing changed
I tried to reinstall .Net (I`m using 4.5.2)
Installed Windows 10 SDK
Tried to import with global
Added
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
Added System.Runtime.dll reference
Example code which probably is useless for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.QueryStringDotNET;
using Windows.UI.Notifications;
namespace MessagerClient.Notifications {
class DefaultWindowsNotification {
public static void notificationTest() {
string title = "Andrew sent you a picture";
string content = "Check this out, Happy Canyon in Utah!";
string image = "http://blogs.msdn.com/something.jpg";
string logo = "ms-appdata:///local/Andrew.jpg";
ToastVisual visual = new ToastVisual() {
BindingGeneric = new ToastBindingGeneric() {
Children =
{
new AdaptiveText()
{
Text = title
},
new AdaptiveText()
{
Text = content
},
new AdaptiveImage()
{
Source = image
}
},
AppLogoOverride = new ToastGenericAppLogo() {
Source = logo,
HintCrop = ToastGenericAppLogoCrop.Circle
}
}
};
Console.WriteLine("NOTIFICATION");
//Can`t use because of Windows.UI library
ToastNotificationManager.CreateToastNotifier().Show(visual);
}
}
}
You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:
Edit the .csproj file with a text editor, Notepad will do. Insert this:
<PropertyGroup>
<TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
</PropertyGroup>
Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.
Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.
Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:
using Windows.UI.Notifications;
...
private void button1_Click(object sender, EventArgs e) {
var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var text = xml.GetElementsByTagName("text");
text[0].AppendChild(xml.CreateTextNode("Hello world"));
var toast = new ToastNotification(xml);
ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}
Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.
If anyone should happen to stumble on this, see this similar but newer post -
Toast Notifications in Win Forms .NET 4.5
Read Stepan Hakobyan's comment at the bottom.
Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.
A follow up to:
OpenGL4Net WM_PAINT does not exist?
I am still closely following: https://sourceforge.net/p/ogl4net/wiki/Tutorials
The program as it currently stands:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenGL4NET;
namespace pads2
{
class Program : Form
{
private const int WM_PAINT = 15;
RenderingContext rc;
static void Main(string[] args)
{
Program program = new Program();
program.Init();
Application.Run(program);
}
// required for open GL
void Init()
{
rc = RenderingContext.CreateContext(this);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
void Render()
{
gl.Clear(GL.COLOR_BUFFER_BIT);
// here is the right place to draw all your scene
rc.SwapBuffers();
}
// change window size
protected override void OnSizeChanged(EventArgs e)
{
gl.Viewport(0, 0, ClientSize.Width, ClientSize.Height);
// projection matrix may also need adjusting
}
// required for open GL
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_PAINT: Render(); break;
default: base.WndProc(ref m); break;
}
}
}
}
Q: Provided that I'm implementing the tutorial correctly, what can I do about the error System.BadImageFormatException on line program.Init();?
Additionally:
Additional information: Could not load file or assembly 'OpenGL4Net,
Version=4.3.37.24, Culture=neutral, PublicKeyToken=null' or one of its
dependencies. An attempt was made to load a program with an incorrect
format.
This could be due to the warning:
There was a mismatch between the processor architecture of the project
being built "MSIL" and the processor architecture of the reference
"OpenGL4Net", "AMD64". This mismatch may cause runtime failures.
Please consider changing the targeted processor architecture of your
project through the Configuration Manager so as to align the processor
architectures between your project and references, or take a
dependency on references with a processor architecture that matches
the targeted processor architecture of your project.
However according to:
How do I fix the Visual Studio compile error, "mismatch between processor architecture"?
This should not be an issue. There is only the option of (32 or 64) bit when downloading the OpenGL4Net DLL.
Given that Microsoft Intermediate Language is not the same as a processor, I tried running in release mode instead of debug mode, but it makes no difference.
What build configuration do you use when compiling? And what version of OpenGL4Net did you download? The 32 or 64 bit version?
Try setting the build configuration to match the intended target cpu of the referenced assembly (so, either 32 or 64 bit, depending on the download of OpenGL4Net).
See C# compiling for 32/64 bit, or for any cpu? for a detailed explanation.
This question already has answers here:
The name 'InitializeComponent' does not exist in the current context
(51 answers)
Closed 4 years ago.
Hi I am getting an error of InitializeComponent in my app.xaml.cs page I have checked the net and everything but no solution works. Please help.
InitializeComponent does not exist
C# file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
namespace Miser_sApp
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Disable the application idle detection by setting the UserIdleDetectionMode property of the
// application's PhoneApplicationService object to Disabled.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
XAML file:
<Application
x:Class="Miser_sApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
I have uploaded the app.xaml contents.
I have not made any changes in it.
There are two potential causes of this.
The most common is the x:Class doesn't match up with the MainPage.xaml namespace. Make sure that x:Class in MainPage.xaml has the correct namespace.
The second most common cause of this problem is that the "Build Action" is not set to "Page" for MainPage.xaml!
This is the same question and answer here:
The name 'InitializeComponent' does not exist in the current context
You might get this error when you import a class from another project, or change the path of the xaml file, or the namespace of either the xaml or behind .cs file.
One: It might have a namespace that is not the same as what you have in you new project
namespace TrainerB.MVC.Forms
{
public partial class AboutDeveloper : ContentPage
{
public AboutDeveloper()
{
InitializeComponent();
}
}
}
As you can see the name space in the imported file begins with the old project name: "TrainerB", but your new project might have a different name, so just change it to the correct new project name, in both the .xaml file and the behind .cs file.
Two:
change the properties of the .xaml file to:
Build Action: Embedded Resource
Custom Tool: MSBuild:UpdateDesignTimeXaml
Ensure the BuildAction of your App.xaml is set to "ApplicationDefinition"
Delete the "obj" folder in the project, rebuild.
If the problem persist, get rid of the "_" character in your namespace.
I had the same build error but the build action was already set to Page. Trying Build Action set to ApplicationDefinition (error: there can only one instance of that), and setting it back to Page, fixed the build error. Sounds like black magic, but it worked for me.
In my case, I had set build action of XAML page to Embedded Resource,
reverting it to Page fixed the issue.
Here's one other possibility, after exhausting all the above (as well as a few others scattered about the internet): make sure that your Startup object is correctly set to [Project].App in your Project Properties > Application tab.
I had renamed some namespaces, and somewhere in the process VS set the Startup object to "(not set)".
My solution was to set the Build Action property of Package.appxmanifest to AppxManifest. :)
1) In the xaml file, check the x:Name of the main layout. Rename it
2) Compile. It should throw errors
3) Go back to the xaml file and give the same class name as it associated code behind file has (.cs file) Also include the namespace. eg: if namespace is "X" and class name is "Y", x:Name = "X.Y"
4) Compile. It should work.
After successful builds, when the error occurs, close VS, delete the hidden .vs folder in your project (this clears intellisense). Open VS, the error is gone.
This worked for me, Try Ctrl+S on the pages that give you this error.
The error came about, when my visual studio crashed(restarted). The pages I was working on(before the restart) didnt failed to build.
Which lead me to think the didnt save correctly. Hence, Ctrl+S. That solved my issue.
I'm trying to write a simple program that I'm going to be using inside another program for playing back audio and video files using the Microsoft.DirectX.AudioVideoPlayback.dll file. I've got the code listed below since it doesn't have to be incredibly complex. The problem that I am having is that... well, the program does nothing. Not even the main window shows up and I don't know why. I'm using .Net 4.0 and the DirectX DLL version says it's 1.0.2902.0. I tried moving the initialization for the audio and video files to different places (The load event and the button press event specifically). When in the button press event, the form loads, but as soon as I press a button, the program hangs. No errors or anything. Anyone know what is going on here? If someone has a better idea for playing audio and video files, I'm willing to consider that too.
using Microsoft.DirectX.AudioVideoPlayback;
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 MediaPlayer
{
public partial class Player : Form
{
Audio derp;
Video herp;
public Player()
{
InitializeComponent();
this.derp = new Audio("<Audio File Name>");
this.herp = new Video("<Video File Name>");
this.herp.Owner = this.panel1;
}
private void btnPlayPauseStop_Click(object sender, EventArgs e){
switch(((Button)sender).Text){
case "Play":
if (!herp.Playing)
herp.Play();
break;
case "Pause":
if (!herp.Paused)
herp.Pause();
break;
case "Stop":
if (!herp.Stopped)
herp.Stop();
break;
}
}
private void Player_Load(object sender, EventArgs e)
{
}
}
}
I have been using this for making my very own "Media Player Classic" clone
Be sure to debug this in 32 bit mode:
Project Menu --> {project} Properties ... --> Build --> Platform Target = x86
For video, I do not load Audio (it gets done automatically). So instead of using both, use only the one needed (video or audio)
The next thing is to ensure that the panel is visible and big enough to see (check the size after "new Video(...)")
So i have simple application, just a few lines:
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;
using Microsoft.DirectX.DirectInput;
namespace asdasd
{
public partial class Form1 : Form
{
public Device joystick;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (
DeviceInstance di in
Manager.GetDevices(
DeviceClass.GameControl,
EnumDevicesFlags.AttachedOnly))
{
joystick = new Device(di.InstanceGuid);
break;
}
if (joystick == null)
{
throw new Exception("No joystick found.");
}
}
}
}
and i try to get the active joystick on my computer, but i get error:
i have the assembly Microsoft.DirectX.DirectInput and i have directX SDK 2010 installed.
Can someone tell me where is the problem?
Try adding this to the config file:
http://devonenote.com/2010/08/mixed-mode-assembly-error-after-upgrading-to-dotnet-4-0/
(if configuration already exists, just merge these in)
And, maybe it's not the right place, but just take a look at XNA... Things are usually much easier with that.
I couldn't paste the XML directly here, it doesn't show up.
The DirectX assemblies are built against .NET v1.1 Microsoft stopped actively developing them before .NET v2.0 was released.
They cannot be used in projects targeting other than .NET v1.1. XNA is the "blessed" path forward for managed access to Direct X features. I don't know all if it's features, but SlimDX appears to give a more Direct X feeling API for C# than XNA, though I have not used it, I've heard a lot about it.
You might find better responses for chosing an upgrade path over at gamedev.stackexchange.com though.