I want to define my own Cursor as the Current Cursor in my WPF Application, but wenn I try to create a new Cursor Object from my .cur File, I get an Error.
My Code is
private void NewFile()
{ ...
iEvent_dragdrop = (HTMLDocumentEvents2_Event)doc;
iEvent_dragdrop.ondragstart += new HTMLDocumentEvents2_ondragstartEventHandler(IEvent_ondragstart);
}
private bool IEvent_ondragstart(IHTMLEventObj pEvtObj)
{
x_start = pEvtObj.x; // Read position of Mouse
y_start = pEvtObj.y;
....
if (File.Exists("MyCursor.cur"))
{
System.Windows.Forms.Cursor myCursor = new System.Windows.Forms.Cursor(GetType(), "MyCursor.cur");
System.Windows.Forms.Cursor.Current = myCursor;
//System.Windows.Forms.MessageBox.Show("File exist");
}
else System.Windows.Forms.MessageBox.Show("File does not exist");
return false;
}
When I try to drag the HTML Object, I get the error System.NullReferenceException wasn´t handled in the source-code. But I tested if the File exists ....
Can anyone tell me, what´s my mistake?
Thanks!
I recommend searching the web before asking. First search result for the title explains everything you should need to know.
Try this out:
class Program {
[System.STAThread]
static void Main(string[] args) {
byte[] cursorBytes = new System.Net.WebClient().DownloadData(#"https://github.com/tlorach/nvGraphy/raw/master/cursor1.cur");
System.IO.Stream cursorStream = new System.IO.MemoryStream(cursorBytes, false);
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(cursorStream);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
}
}
Or this:
class Program {
[System.STAThread]
static void Main(string[] args) {
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Filter = "Cursor (*.cur)|*.cur";
switch(openDialog.ShowDialog()) {
case System.Windows.Forms.DialogResult.OK:
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(openDialog.FileName);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
break;
}
}
}
Related
I have converted my old StartActivityForResult code to the new RegisterForActivityResult as StartActivityForResult is depreciated in the android API 29 and higher. My new code works perfectly, except that result in class ActivityResultCallback is always null. I need to be able to know when the user cancels the taking of the picture when they hit the back button, otherwise the app crashes (if a previous picture doesn't already exist) or a previously taken picture is processed again. My code (showing only the relevant code):
public class Photo : AppCompatActivity
{
public ImageView MyImageView;
public ImageButton camerabutton;
public bool PictureTaken = false;
private CurrentSubjectInfo MySubjectInfo;
private ActivityResultCallback _activityResultCallback;
private ActivityResultLauncher _activityResultLauncher;
private Uri uri;
protected override void OnCreate(Bundle bundle)
{
try
{
_activityResultCallback = new ActivityResultCallback();
_activityResultCallback.OnActivityResultCalled += ActivityResultCallback_ActivityResultCalled;
_activityResultLauncher = RegisterForActivityResult(new ActivityResultContracts.TakePicture(), _activityResultCallback);
RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
base.OnCreate(bundle);
SetContentView(Resource.Layout.Photo);
PictureTaken = false;
MySubjectInfo = new CurrentSubjectInfo("", "", "", "", "");
// retrieve subject information from previous activity
MySubjectInfo = Mybundle.GetParcelable("MySubjectInfo", Java.Lang.Class.FromType(typeof(CurrentSubjectInfo))) as CurrentSubjectInfo;
ImageButton camerabutton = FindViewById<ImageButton>(Resource.Id.button1);
MyImageView = FindViewById<ImageView>(Resource.Id.imageView1);
camerabutton.Click += (sender, evt) =>
{
var cameraispresent = CheckCameraHardware();
if (cameraispresent)
{
try
{
// get directory where pictures are stored
App._dir = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
// build file name
MySubjectInfo.Name = MySubjectInfo.Name.Replace(",", "");
MySubjectInfo.Name = MySubjectInfo.Name.Replace(" ", "");
MySubjectInfo.Name = MySubjectInfo.Name.Replace(".", "");
var filename = MySubjectInfo.Name + ".jpg";
App._file = new File(App._dir, String.Format(filename, Guid.NewGuid()));
uri = FileProvider.GetUriForFile(this, this.ApplicationContext.PackageName + ".provider",App._file);
// launch camera activity
_activityResultLauncher.Launch(uri);
}
catch (Exception e)
{
// trap error and log it
};
}
};
}
}
Boolean CheckCameraHardware()
{
Android.Content.PM.PackageManager pm = PackageManager;
if (pm.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCamera))
{
// this device has a camera
return true;
}
else
{
// no camera on this device
return false;
}
}
private void ActivityResultCallback_ActivityResultCalled(object sender, ActivityResult result)
{
// result is always null, so I don't check it
try
{
// Because the resulting bitmap is rotated and too large, I set original orientation and resize
// suffice it to say it works perfectly so I won't post the code here
int height = 260;
int width = 200;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
Bitmap bitmap = App.bitmap;
var filePath = App._file.AbsolutePath;
// save the resized bitmap, overwriting original file
var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Close();
// set the imageview to the resulting bitmap
MyImageView.SetImageBitmap (App.bitmap);
// cleanup
bitmap = null;
App.bitmap = null;
PictureTaken = true;
}
catch (Exception ex)
{
PictureTaken = false;
// trap and log error
}
}
}
This is the ActivityResultCallback class:
public class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
public EventHandler<ActivityResult> OnActivityResultCalled;
public void OnActivityResult(Java.Lang.Object result)
{
ActivityResult activityResult = result as ActivityResult;
OnActivityResultCalled?.Invoke(this, activityResult);
}
}
As stated all this code executes perfectly with no errors except that Java.Lang.Object result is always null. I need to know when the user cancels the camera activity, I would assume that Java.Lang.Object result would indicate cancelled but I get nothing. What am I missing?
Ok, after some playing around I noticed that the parameter Java.Lang.Object result in the ActivityResultCallback class was either true or false depending on what the user did with the camera. So I changed the class to:
public class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
public EventHandler<ActivityResult> OnActivityResultCalled;
public void OnActivityResult(Java.Lang.Object result)
{
ActivityResult activityResult;
if ((bool)result)
{
activityResult = new ActivityResult((int)Result.Ok, null);
} else
{
activityResult = new ActivityResult((int)Result.Canceled, null);
}
OnActivityResultCalled?.Invoke(this, activityResult);
}
}
In the ActivityResultCallback_ActivityResultCalled function, I modified it to this:
private void ActivityResultCallback_ActivityResultCalled(object sender, ActivityResult result)
{
try
{
if (result.ResultCode == (int)Result.Ok)
{
int height = 260;
int width = 200;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
Bitmap bitmap = App.bitmap;
var filePath = App._file.AbsolutePath;
var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Close();
MyImageView.SetImageBitmap(App.bitmap);
bitmap = null;
App.bitmap = null;
PictureTaken = true;
}
}
catch (Exception ex)
{
// trap and log error
}
}
activityResult apparently has, at a minimum, two parameters, the result and data. I already had what I needed for data so I set that to null and cast Result.Ok or Result.Cancelled to int depending on whether result was true or false. I still don't totally understand how to use the new ActivityForResult API, but this works for me and I'm running with it.
I am trying to create a program for my project in school, and I have come across a problem. I am using LinqPad premium and when I launch the program it starts fine. However, when I try and start it for the second or third time it throws the exception:
"ObjectDisposedException: Cannot access a disposed object."
"Object name: 'Form'."
Here is my code:
void Main()
{
MenuClass.Main();
}
class MenuClass
{
static public Form MenuWindow = new Form();
static public void Main()
{
MenuWindow.Height = 300;
MenuWindow.Width = 300;
MenuWindow.Text = "Menu";
Button btnPlay = new Button();
btnPlay.Left = 10;
btnPlay.Top = 290;
btnPlay.Text = "Reset";
//btnPlay.Click += btnReset_click;
Button btnTakeTurn = new Button();
btnTakeTurn.Left = 10;
btnTakeTurn.Top = 270;
btnTakeTurn.Text = "Take Turn";
//btnTakeTurn.Click += btnTakeTurn_click;
Graphics g = MenuWindow.CreateGraphics();
MenuWindow.Controls.Add(btnPlay);
MenuWindow.Controls.Add(btnTakeTurn);
//MenuWindow.Paint += f_Paint;
MenuWindow.Show();
}
}
The error occurs where it says "Graphics g = MenuWindow.CreateGraphics();"
and also when i take that out it does it on "MenuWindow.Show();"
Please help, as I am powerless in this situation.
Change:
static public Form MenuWindow = new Form();
static public void Main()
{
to:
static public void Main()
{
var MenuWindow = new Form();
to ensure that each invocation generates a new form.
In C#.NET, I am trying to add controls from a static class to a non-static class.
This is my code:
public static void AddMediaToPanel(string Title, string Description, string Source, string Cover, string Genre, int Rating)
{
PictureBox MediaCanvas = new PictureBox();
MediaCanvas.BackColor = Color.LightGray;
MediaCanvas.BorderStyle = BorderStyle.FixedSingle;
MediaCanvas.Size = new Size(150, 235);
MediaCanvas.Padding = new Padding(10);
try
{
MediaCanvas.ImageLocation = Source;
}
catch { }
var gui = new GUI();
gui.Controls.Add(MediaCanvas);
}
The GUI method stands for a Windows Form called 'GUI'.
I'm trying to make an open-source media center that allows you to add movies
to a repository.
The static void AddMediaToPanel must be static, because of this class:
public static void RetrieveMedia(string XMLFile)
{
// Declare the Media Collections
MediaCollection media = null;
// Declare the XML-readers
XmlSerializer serializer = new XmlSerializer(typeof(MediaCollection));
StreamReader sr = new StreamReader(XMLFile);
try
{
media = (MediaCollection)serializer.Deserialize(sr);
}
catch(Exception ex)
{
MessageBox.Show("The following media repository could not be loaded:\n" +
XMLFile + "\n" +
"Please check your code and try again later.\n\n" +
"Error Information: " + ex.Message, "Repository error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
// Create new instance of the media class
sr.Close();
// Return properties
try
{
foreach (Video video in media.Video)
{
GUI.AddMediaToPanel(video.Title, video.Description, video.Source, video.Cover, video.Genre, video.Rating);
}
}
catch { }
}
I'm using .NET Framework 4.5.2.
Thanks in advance!
~ Kees van V.
This can't work this way. In your loop you are calling your static method:
foreach (Video video in media.Video)
{
GUI.AddMediaToPanel(video.Title, video.Description, video.Source, video.Cover, video.Genre, video.Rating);
}
But your static method creates a new Form each time, adds a control to it, then throw it away:
var gui = new GUI();
gui.Controls.Add(MediaCanvas);
You need to create your form once (outside of your static method), then have your static method return a control that you can add to your single Form instance.
Your instance method with the loop could look like:
var gui = new GUI();
foreach (Video video in media.Video)
{
var control = GUI.AddMediaToPanel(video.Title, video.Description, video.Source, video.Cover, video.Genre, video.Rating);
gui.Controls.Add(control);
}
In your current code you just create and throw away the gui form:
var gui = new GUI();
gui.Controls.Add(MediaCanvas);
You have to find the form instance you want the controls be added to:
public static GUI CurrentGui {
get {
GUI gui = Application
.OpenForms
.OfType<GUI>()
.LastOrDefault();
// no such form found, you may want to create the form
if (null == gui) {
gui = new GUI();
gui.Show(); // <- let's show it up
}
return gui;
}
}
...
public static void AddMediaToPanel(...) {
...
CurrentGui.Add(MediaCanvas);
}
I am developing a chat application using jabber-net opensource library..
my aim is to display a form (chat window ) when a message is coming.
But when I use this code, Form appears in the task bar,,, not perfectly rendered...
seems like this... More over I can see the form only when I mousehover the Icon on taskbar (Hail Windows 7)... Any form are like this...
Click here for Output Image
my code is this...
public jabber.client.JabberClient jabberClient1;
jabberClient1.User = UserName;
jabberClient1.Password = Password;
jabberClient1.Resource = resource;
jabberClient1.AutoRoster = true;
jabberClient1.OnMessage += new MessageHandler(jabberClient1_OnMessage);
private void jabberClient1_OnMessage(object sender, jabber.protocol.client.Message msg)
{
try
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}
you have to use chw.ShowDialog()
or use if invokerequired
private delegate void dlgInvokeRequired();
public void InvokeMethode()
{
if (this.InvokeRequired == true)
{
dlgInvokeRequired d = new dlgInvokeRequired(InvokeMethode);
this.Invoke(d);
} else
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}
I have solved it myself...
I have to use
JabberClient1.InvokeControl = FormInstance;
and, the FormInstance should be shown Before the chat window appears....
ie, It can be the contact window (Roster)....
I have another WPF Window i've created.. say window2.xaml. I have a button.. and on click i want it to load that window.. i've tried Googling but nothing seems to be working. It just loads a blank page. I know this is really simple, but I really can't find how to do it through my searches.
This is what i have tried:
GameClock temp = new GameClock();
temp.ShowDialog(); //just shows blank window
temp.Show(); //just shows a blank window too
EDIT: I figured out the problem. I took out the initialize component because there an an error. I thought it was something only the main window needed. When I put it back, it works. Thanks, everyone.
try this... u can use like a generic methode
private void button_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
OpenWin("window2", new Uri(#"window2.xaml", UriKind.Relative), "Window2Label");
}
catch (Exception ex)
{
Message.Show(ex);
}
}
public static DocumentPanel OpenWin(string namePainelItem, Uri xamlPath, string caption = "", RoutedEventHandler unloadEvent = null, bool closeOpenWin = false)
{
try
{
if (closeOpenWin)
{
CloseWin(namePainelItem, false);
}
DocumentPanel panel1 = GetWin(namePainelItem);
if (panel1 == null)
{
panel1 = new DocumentPanel();
panel1.Caption = caption;
panel1.Name = namePainelItem;
panel1.Content = xamlPath;
if (unloadEvent != null)
{
panel1.Unloaded += unloadEvent;
}
hdl.dockLayoutManager.DockController.Insert(hdl.documentGroup1, panel1, 1);
hdl.dockLayoutManager.DockController.ActiveItem = panel1;
}
else
{
if (panel1.Visibility != Visibility.Visible)
panel1.Visibility = Visibility.Visible;
if(panel1.IsClosed)
panel1.Closed = false;
hdl.dockLayoutManager.DockController.ActiveItem = panel1;
}
return panel1;
}
catch (Exception ex)
{
Message.Show(ex);
}
return new DocumentPanel();
}
public static void CloseWin(string namePainelItem)
{
try
{
BaseLayoutItem item = hdl.dockLayoutManager.GetItem(namePainelItem);
if (item != null)
{
hdl.documentGroup1.Items.Remove(item);
hdl.dockLayoutManager.DockController.RemovePanel((DocumentPanel)item);
item = null;
}
}
catch (Exception ex)
{
Message.Show(ex);
}
}
You may need to read the XAML file before creating the instance of GameClock. Something like this:
GameClock clock;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
clock = (GameClock)XamlReader.Load(fs);
JAB