问题描述
我有一个Xamarin.Mac应用程序,需要在登录时自动打开.我如何让我的应用程序获得此设置,而无需手动单击它?
I have a Xamarin.Mac app that needs to open automatically at login.How do I have my application get this setting without having to manually click on it?
推荐答案
由于Xamarin.Mac不支持 LSSharedFileList库,因此必须使用Xcode创建dylib并将其绑定到Xamarin中. Mac应用程序.
Since the LSSharedFileList library is not supported on Xamarin.Mac you have to create a dylib with Xcode and bind it in your Xamarin.Mac application.
1)在Xcode上创建Dylib项目.添加此功能:
1) Create a Dylib project on Xcode. Add This function:
-(BOOL)AddLoginItem:(NSString *) AppPath{
// Your have to send this string as argument(i.e: on a textbox, write: /Applications/Calculator.app/)
// Get Login Items
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (loginItems) {
NSLog(@"[DEBUG]Your Application Path:%@",AppPath);
// Covert String to CFURLRef (It adds "file://" to your itemUrl1)
CFURLRef appUrl = (__bridge CFURLRef)[NSURL fileURLWithPath:(NSString*) AppPath];
NSLog(@"[DEBUG] appUrl:%@", appUrl);
// Now we add the requested Login Item
LSSharedFileListItemRef itemRef = LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemLast, NULL, NULL, appUrl, NULL, NULL);
// Confirm that your path was correct and that you got a valid Login Item Reference
NSLog(@"[DEBUG]Item:%@", itemRef);
if (itemRef) CFRelease(itemRef);
// Your item just got added to the user's Login Items List
CFRelease(loginItems);
return true;
}
return false;
}
2)创建一个可可项目,其中包含一个TextBox,一个Push按钮以及其中的Actions和Outlets控件. 使用此链接可以帮助您处理来自Objective-C DLL的C#绑定.
2) Create a Cocoa project with an TextBox, a Push button and their Actions and Outlets controls in it. Use this link to help you with the C# bindings from a objective-c DLL.
3)在Xamarin.Mac项目的MainWindow.cs中,添加以下代码并进行必要的更改以适合您的代码. 不要忘记添加在上一个链接上创建的.Net程序集引用,以及您的:using DLLloginItem;.线.
3) On your Xamarin.Mac project, in MainWindow.cs, add the following code and make the necessary changes to fit on your code. Don't forget to add your .Net Assembly reference, created on the previous link and also your: using DLLloginItem; line.
// Some variables
private string TestItemName;
private bool rem;
// Button Click
partial void AddItemButton (Foundation.NSObject sender) {
LoginItemsDLL loginItem = new LoginItemsDLL();
// Enter this string on your TextBox TxtName /Applications/Calculator.app/
TestItemName = TxtName.StringValue;
rem=loginItem.AddLoginItem(TestItemName);
Console.WriteLine(rem);
}
为了输入您的应用程序路径,请使用另一个函数,该函数仅接收应用程序名称并将其路径返回到AddLoginItem参数中.希望对您有帮助!
In order to get your application path entered, use another function that just receives the application name and returns its path into AddLoginItem argument. Hope it helps!
这篇关于如何使Xamarin.Mac应用“登录时打开"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!