Hello I tried creating a rectangle in a wpf application and I'm recieving this error I tried googling it but it didn't work.
Error:
The calling thread must be STA, because many UI components require this.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
namespace Game
{
class Engine
{
#region Members
private Thread _render;
#endregion
public Engine()
{
_render = new Thread(new ThreadStart(Render));
_render.Start();
}
private void Render()
{
while (true)
{
Rectangle rect = new Rectangle();
}
}
}
}
I think this would fix it:
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => this.progressBar.Value = 50));
But doesn't that take away the purpose of using a different thread because then all the rendering would still be done on the main thread.
And another question:
I'm trying to draw rectangles of 1 by 1 and detect collision if they "fall" on each other(a loop sets their x--).
Could I also do this with pixels?
Rendering should always be performed on the main thread. That is a design thing in Windows / Win32.
Thanks to the original design of Win32 (which involves handles to windows, aka hWnd's), the thread calling the painting operation must be the same as the one doing the actual painting.
There is a nice article on MSDN about the Threading model and WPF.
Related
In a UWP C# app, need background (ie. worker) thread to use UI thread to display an image. But can't figure out how to compile Dispatcher.RunAsync().
using Foundation;
using System;
using UIKit;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
using System.Windows.Threading; <<<<<<<<<< gets error
using Windows.UI.Core; <<<<<<<<<< gets error
public async static void process_frame()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// "the name dispatcher does not exist in current context"
//UI code here:
display_frame();
});
}
public void display_frame()
{
var data = NSData.FromArray(System_Hub_Socket.packet_frame_state.buffer);
UIImageView_camera_frame.Image = UIImage.LoadFromData(data);
}
Latest method
public async static void process_frame( /* ax obsolete: byte[] camera_frame_buffer, int frame_size_bytes */ )
{
await Task.Run( () => { viewcontroller.display_frame(); } );
}
// [3]
// Copies latest frame from camera to UIImageView on iPad.
// UI THREAD
public Task display_frame()
{
var data = NSData.FromArray ( System_Hub_Socket.packet_frame_state.buffer);
<<<<<< ERROR
UIImageView_camera_frame.Image = UIImage.LoadFromData( data );
return null;
}
Error from the latest method
Looking at the using statements in you code:
using UIKit;
...
using Windows.UI.Core;
This just can't happen. UIKit is a Xamarin.iOS, platform-specific namespace and Windows.UI.Core is Windows platform-specific namespace and in no way can those two be mixed in one file (except for shared project with #if directives that is, but that is not the case here).
Xamarin helps writing cross-platform apps, but you still cannot use platform specific APIs on OS on which they are not available. Windows has Dispatcher as a means of running code on the UI thread, but this concept is not available on iOS, which uses InvokeOnMainThread method instead.
So if you are writing code that is in the platform-specific iOS project, you must use iOS APIs. If you are writing code that is in the platfrom-specific UWP project, you must use UWP APIs - things like Dispatcher will work without problem there.
Finally, if you are writing code in a .NET Standard library, you cannot write any platform specific code directly and must use dependency injection to define an interface behind which you hide the use of platform specific APIs.
I'm trying to follow this answer https://stackoverflow.com/a/47295752/1237135, in order to get a list of IIS Express websites, which involves referencing Microsoft.Web.dll (this is a .NET assembly, but presumably it uses COM calls) and calling this code
using (var runtimeStatusClient = new RuntimeStatusClient())
{
var workerProcess = runtimeStatusClient.GetWorkerProcess(19464);
//there's more but this is all that is needed for failure
}
It actually works, the code runs and has meaningful data, however a few seconds after it completes I get this error
System.InvalidCastException:
'Unable to cast COM object of type 'System.__ComObject'
to interface type 'Microsoft.Web.RuntimeStatus.IRsca2_WorkerProcess'.
This operation failed because the QueryInterface call on the COM component
for the interface with IID '{B1341209-7F09-4ECD-AE5F-3EE40D921870}' failed
due to the following error: No such interface supported (Exception from
HRESULT: 0x80004002 (E_NOINTERFACE)).'
E_NOINTERFACE is often associated with not using an STAThread model, but I've verified that the thread is STA.
The code works without error in a Console app environment, but not WPF.
The answer above mentions
I looked into RegisteredUrlsInfo (in Microsoft.Web.dll) as well and
found that it's using two COM interfaces,
IRsca2_Core (F90F62AB-EE00-4E4F-8EA6-3805B6B25CDD)
IRsca2_WorkerProcess (B1341209-7F09-4ECD-AE5F-3EE40D921870)
And I saw another answer https://stackoverflow.com/a/1058978/1237135 that talks about
Try adding this to your App.exe.manifest:
iid="{C677308A-AC0F-427D-889A-47E5DC990138}"
proxyStubClsid32="{00020424-0000-0000-C000-000000000046}"
baseInterface="{00000000-0000-0000-C000-000000000046}" tlbid =
"{PUT-YOUR-TLB-GUID-HERE}" /> Where TLBID can be found from your
Visual Studio generated Native.Namespace.Assembly.Name.manifest,
looking like this:
but I'm unclear if this applies here.
I also wondered if it's DLL Hell but that wouldn't explain why it works from a Console, would it?
EDIT: minimal reproduction.
Create a WPF project (I used 4.6.1 runtime) and in the codebehind for the MainWindow I used
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
using (var runtimeStatusClient = new Microsoft.Web.RuntimeStatus.RuntimeStatusClient())
{
var workerProcess = runtimeStatusClient.GetAllWorkerProcesses();
}
}
}
}
The only hard part is you need to find and reference Microsoft.Web.DLL (which if you have IIS Express on your machine should be in your GAC). You can do a Windows search on your C:\ drive and it will probably be somewhere like C:\Windows\assembly\GAC_MSIL\Microsoft.Web\7.1.0.0__31bf3856ad364e35
Do that and you'll see the problem.
Apparently I made 2 fatal assumptions:
Console Apps use STA. However this isn't true, it seems by default they are MTA. That figures I suppose as desktop apps have to explicitly state STA in the Main method.
To do COM interop you have to use STA. I assumed this because using STA is the go-to solution to E_NOINTERFACE problems on the web. However as I understand it now, some COM can use MTA. It appears for Microsoft.Web.DLL, you need MTA.
So my solution is to create a new thread (which will use MTA by default), eg.
public MainWindow()
{
InitializeComponent();
//Do use ThreadPool instead of this...
Thread thread = new Thread(new ThreadStart(() => { GetWebsites(); }));
thread.Start();
}
void GetWebsites()
{
This question already has an answer here:
How do I lock a windows workstation programmatically? [duplicate]
(1 answer)
Closed 5 years ago.
I want to implement an app that locks my open session on Windows 10, when an event occurs. I saw more or less the same question here , and the answer seems to say, there is no way to lock the Windows screen programatically. However, I already saw some applications do lock Windows screen (for example, Nymi Companion Device Application).
Do you know how to implement the locker? Or which module allow to achieve the task?
This is a complete sample code in c#
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 System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern bool LockWorkStation();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
LockWorkStation();
}
}
}
This works:
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern void LockWorkStation();
I am confused as to why a Window will not appear with the below code. Am I missing an import?
using System.Text;
using System.Xml;
using System.Windows;
using System;
using System.Windows.Forms;
using System.IO;
using System.Threading;
public class Program {
public Window mainWindow;
static void main() {
// Create the application's main window
mainWindow = new Window();
mainWindow.Title = "Enter SN";
mainWindow.Show();
}
}
You want to run your Window via an Application.Run() call. Your current code will not fire it off on a standard windows message loop, which is required.
Remove your Show() call and replace it with:
Application.Run(mainWindow);
To be even simpler, if you set your title as your wish on your WinForms designer, your main can be a single line:
Application.Run(new Window());
Also, you have many unnecessary using statements. These statements aren't a real problem, just unnecessary and confusing.
I am using .NET Remoting. My server/hoster is a Windows Service. It will sometimes work just fine and other times it will process one request and then it does not process any more (until I restart it). It is running as a Windows service Here is the code from the Windows Service:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.ServiceProcess;
using System.Text;
using Remoting;
namespace CreateReview
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
readonly TcpChannel channel = new TcpChannel(8180);
protected override void OnStart(string[] args)
{
// Create an instance of a channel
ChannelServices.RegisterChannel(channel, false);
// Register as an available service with the name HelloWorld
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(SampleObject),
"SetupReview",
WellKnownObjectMode.SingleCall);
}
protected override void OnStop()
{
}
}
}
Thanks for any help offered.
Vaccano
as a SingleCall type, your SampleObject will be created for every call the client makes. This suggests to me that your object is at fault, and you don't show what it does. You need to look at any dependancies it has on shared resources orlocks. Try writing some debug out in the SampleObject's constructor to see how far the remoting call gets.